How To: Create A Collection for Each AD Site in the Current Forest

Here’s an example of leveraging PowerShell to query AD to find all Active Directory Sites, and then create a collection for each one (unless it already exists) in ConfigMgr 2012:

#update Site Server and Namespace information for SMS Provider
$Server = "myServer"
$NameSpace = "root\sms\site_LAB"
#enter collectionID that will be used as the limiting collection for the new collections.
$CollectionLimiter = "LAB00018"

function CreateCollectionQueryRule($Coll, $Server, $Namespace, $RuleName, $WQL)
#function used to create the rule for the query, based on QueryID.
$wmiclass = "\\" + $Server + "\" + $NameSpace + ":sms_CollectionRuleQuery"
$CollQuery = ([wmiclass] $wmiclass).CreateInstance()
$collquery.QueryExpression = $WQL
$CollQuery.RuleName = $RuleName
$coll = gwmi sms_collection -namespace $Namespace -computer $server | where-object { $_.CollectionID -eq $coll }

#Find ADSites in the current forest
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() 
$ADSites = $forest.get_Sites()

$ADSites | foreach-object {
#see if the collection already exists
$strFilter = "Name='" + $_ + "'"
if ((gwmi sms_collection -namespace $NameSpace -computername $Server -filter $strfilter| measure).count -eq 1) {
"Collection {0} already exists!" -f $_

else {
#Collection doesn't exist, create new collection and rule now
$strWQL = "Select resourceid from SMS_R_System where SMS_R_System.ADSiteName = '$_'"
$Path = "\\" + $Server + "\" + $NameSpace + ":SMS_Collection"
$coll = ([wmiclass] $path).CreateInstance()
$coll.Name = $_.Tostring()
#Create refresh schedule - run once a week on Saturdays
$Path = "\\" + $server + "\" + $Namespace + ":SMS_ST_RecurInterval"
$refreshSchedule = ([wmiclass] $path).CreateInstance()
$refreshSchedule.DaySpan = 7
$refreshSchedule.StartTime = "20120804060000.000000+***"
$coll.RefreshSchedule = $refreshSchedule
$coll.RefreshType = 2 #use a value of 6 if you want to enable dynamic collections
#save the collection
#Create the collection Rule
CreateCollectionQueryRule $Coll.CollectionID $Server $Namespace $_.Name.Tostring() $strWQL

Download CreateCollectionsBasedOnADSites.ps1

About Greg Ramsey
Greg Ramsey is a Distinguished Engineer for Dell Digital - Services. He has a B.S. in Computer Sciences and Engineering from The Ohio State University and has co-authored many books over the years. Greg is also a board member of the Northwest System Center User Group and the Midwest Management Summit. ​Greg has been a Microsoft Endpoint Manager (ConfigMgr, Intune) MVP for over 14 years.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: