How To: Create A Collection for Each AD Site in the Current Forest
August 14, 2012 Leave a comment
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" $wmiclass $CollQuery = ([wmiclass] $wmiclass).CreateInstance() $collquery.QueryExpression = $WQL $CollQuery.RuleName = $RuleName $coll = gwmi sms_collection -namespace $Namespace -computer $server | where-object { $_.CollectionID -eq $coll } $coll.AddMembershipRule($CollQuery) } #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() $coll.LimitToCollectionID=$collectionLimiter #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 $coll.Put() $coll #Create the collection Rule CreateCollectionQueryRule $Coll.CollectionID $Server $Namespace $_.Name.Tostring() $strWQL } }