Create an SCCM collection with Powershell WMI

Automation is the keyword to get rid of repetitive tasks – then you can focus on the real work right?

So here we go again, this time to create a User Collection with the SMS_Collection WMI class.
I only used this function to create user collections, but can easily be modified to create device collections. Link to the WMI class in the bottom.

Also this function uses the log function which you can find here: here

As the same as in other scripts I have defined two global variables in top of the script so it’s not needed to declare server and site when calling the function later on:

$GlobalSCCMSiteServer = "SCCM2016"
$GlobalSCCMSiteCode = "S01"

Here you go:

Function Create-Collection
{
	param ([Parameter(Mandatory=$False)]
        $SCCMSiteServer =$GlobalSCCMSiteServer,
        [Parameter(Mandatory=$False)]
        $SCCMSiteCode = $GlobalSCCMSiteCode,
        [Parameter(Mandatory=$True)]
        $CollectionName,
        [Parameter(Mandatory=$True)]
        $LimitingCollectionID
	)
	$NewColl = ([wmiclass]("\\$SCCMSiteServer\ROOT\sms\site_" + $SCCMsiteCode + ":SMS_Collection")).CreateInstance()
	if ($NewColl)
	{
		$NewColl.Name = $CollectionName
		$NewColl.CollectionType = "1"
		$NewColl.LimitToCollectionID = $LimitingCollectionID
                #Below was not possible, i need to move the collection after creation
		#$NewColl.ParentContainerNodeID = $CollectionNodeID
		$NewColl.Put() | Out-Null
		Write-Log ("Created collection {0}" -f $CollectionName) -Path $Log
	}
	else
	{
		Write-Log -logOutput "There was an error creating the collection: $_" -Path $Log
	}

}

Below i create a collection in the root folder of the user collections named ‘All female users’:

Create-Collection -CollectionName "All female users" -LimitingCollectionID C0002020

Read the whole Microsoft article about the SMS_Collection class here

There it is guys, feel free to leave a comment.

2 thoughts on “Create an SCCM collection with Powershell WMI”

  1. If agent installed you can get site code
    $SC = (new-object -ComObject “microsoft.sms.client”).getassignedsite()

    Reply
    • In larger instances of SCCM, the client’s site code is not always the site code of the server you are communicating with. (CAS vs Primary vs Secondary).

      Use the following to obtain the SiteCode from the server you want to communicate with.

      $SCCMServerName = “your_sccm_server”
      $SiteNameSpace = “root\sms\” + (Get-WmiObject -ComputerName $SCCMServerName -Namespace “root\sms” -class “__NAMESPACE” | Select name).name
      Write-Host “WMI: $SCCMServerName $SiteNameSpace”

      Reply

Leave a comment