Pages

Thursday, March 20, 2014

Add Multiple Discovered/Managed Computer to a Collection - SCCM 2007/2012/2012 R2

After doing some research, here's the script I've used to add a list of computers to a certain collection using a batch file. Basically there are three parts of the script:

1. comp.txt - contains the list of computers to be added
2. addcompresid.vbs - contains the script that adds computers to the collection.
3. batch.bat - contains the script to add computers from comp.txt using addcompresid.vbs script.

Instructions:

1. Copy and create (probably from notepad) the batch.bat and addcompresid.vbs
2. Edit Set objSWbemServices= objSWbemLocator.ConnectServer on addcompressid.vbs to specify which MP you are going to connect.
3. Edit Set _COLID on Batch.bat  to specify the collection ID. This can be found on the properties of the collection. 
4. On the same folder, create comp.txt and paste all the computers to be added.


So here's the script and enjoy! 

_________________________________________________________________
Batch.bat

@echo off
Set _COLID=COLLECTION
Set _log=AddToCollection.log

echo Starting log file > %_log%

for /f %%a in (comp.txt) do call :AddComp %%a

goto :eof 

:AddComp

cscript //nologo AddCompResID.vbs %1 %_COLID%
Echo. Adding Computer %1 to SCCM CollectionID %_COLID%
Echo. Adding Computer %1 to SCCM CollectionID %_COLID% >> %_log%

goto :eof

_________________________________________________________________
addcompresid.vbs

strCompName = Wscript.Arguments.Item(0)
strCollID = Wscript.Arguments.Item(1)

Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices= objSWbemLocator.ConnectServer("MPSERVER","root\sms")

Set ProviderLoc = objSWbemServices.InstancesOf("SMS_ProviderLocation")
For Each Location In ProviderLoc
    If Location.ProviderForLocalSite = True Then
        Set objSWbemServices = objSWbemLocator.ConnectServer _
            (Location.Machine, "root\sms\site_" + Location.SiteCode)
    End If
Next

Set colCompResourceID = objSWbemServices.ExecQuery("SELECT ResourceID FROM SMS_R_System WHERE " & _
                                              "NetbiosName='" & strCompName & "'")

For each insCompResource in colCompResourceID
 strNewResourceID = insCompResource.ResourceID
Next

Set instColl = objSWbemServices.Get("SMS_Collection.CollectionID=""" & strCollID & """")
Set instDirectRule = objSWbemServices.Get("SMS_CollectionRuleDirect").SpawnInstance_()

instDirectRule.ResourceClassName = "SMS_R_System"
instDirectRule.ResourceID = strNewResourceID
instDirectRule.RuleName = strComputerName
instColl.AddMembershipRule instDirectRule

_________________________________________________________________


No comments:

Post a Comment