Got orphaned collections in ConfigMgr?

This one goes back several years to when I was routinely writing code that used the ConfigMgr SDK (although in an odd coincidence, I was writing such code again yesterday).  It was pretty easy to run some buggy code that didn’t quite do what was intended, and as a result ConfigMgr might be left in an odd state.

One example of this: orphaned collections.  These exist in ConfigMgr, and if you look via WMI you can see them.  But they don’t exist in the console anywhere – they are invisible.  This would happen because those collections were not “rooted” to the top-level collection called “COLLROOT” (or any other collection, if you build collection hierarchies).

Other than “buggy code”, how else could these orphaned collections happen?  Good question, hard to say.

So how do you fix these?  Well, simple:  You “re-root” them by creating a new SMS_CollectToSubCollect WMI instance that says “this collection is a subcollection of COLLROOT”.  A long time ago, I wrote a script to do this.  After enough digging around, I found it again, so I’ll provide it here:

Set services = Getobject("winmgmts://YOURSERVER/root/sms/site_XXX")

' Just in case we need to re-root a collection, get the class instance
Set theClass = services.Get("SMS_CollectToSubCollect")

' Get a list of collections.  Make sure each one has a parent.  If not, connect it to COLLROOT.
Set collList = services.ExecQuery("select * from SMS_Collection where CollectionID <> 'COLLROOT' ")
For each c in collList

    ' WScript.Echo "Checking " & c.CollectionID

    ' See if this collection is already associated with the root collection.  If not, fix it.
    Set result = services.ExecQuery("select * from SMS_CollectToSubCollect where subCollectionID = """ & c.CollectionID & """")
    If result.Count = 0 Then
        WScript.Echo "No parent found for " & c.CollectionID

        Set theRelationship = theClass.SpawnInstance_()
        theRelationship.parentCollectionID = "COLLROOT"
        theRelationship.subCollectionID = c.CollectionID
        Set path = theRelationship.Put_
        Set path = Nothing
        Set theRelationship = Nothing

    WScript.Echo "Added " & c.CollectionID & " (" & c.Name & ") to the root collection"

    End If
    Set result = Nothing

Next

Paste this into a text file, change the server name (from “YOURSERVER”) and site code (from “XXX”), save it as “ReRoot.vbs”, and run it using “cscript.exe ReRoot.vbs”.  It will check every collection, and if it finds one that is orphaned, it will “re-root” it to to the root collection, telling you what collection (ID and name) was fixed.  After the script is finished, you can find the “re-rooted” collections in the admin console, and you can decide what to do with them from there.