Wednesday, January 6, 2016

Create Collections from CSV file in SCCM 2007

Here's a script I use often for when we do targeted global deployments, I've combined a create collection script with one that reads from a CSV from the MSDN sample here: https://msdn.microsoft.com/en-us/library/ms974559.aspx .

Saves a lot of time from not using the console.  It reads from a CSV file with Headers defined as "Name" and "CollectionID" saved to c:\csv folder with the file named collections.csv which you can change to your liking.

The collectionID is the parent collection that will be created under.  Why 2 columns?  I like to separate EU, APAC, North America into their own given.  You may need to have parent collection created a head of time to retrieve the CollectionID.

Chances are you are running this on a x64 machine, if so, execute using cscript from c:\windows\syswow64\ instead of c:\windows\system32 or you might get an ADODB error.  You should not need any MDAC components, I'm running this on a Windows 2003 server.

Script contents:

'On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

Set objLoc =  CreateObject("WbemScripting.SWbemLocator")
Set objSMS= objLoc.ConnectServer(strSMSServer, "root\sms")
Set Results = objSMS.ExecQuery     ("SELECT * From SMS_ProviderLocation WHERE ProviderForLocalSite = true")
For each Loc in Results
    If Loc.ProviderForLocalSite = True Then
        Set objSMS = objLoc.ConnectServer(Loc.Machine, "root\sms\site_" & Loc.SiteCode)
    end if
Next
 

strPathtoTextFile = "C:\csv\"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strPathtoTextFile & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM collections.csv", _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    strColName=objRecordset.Fields.Item("Name")
    strParentID=objRecordset.Fields.Item("CollectionID")
    wscript.echo strColName & " " & strParentID
    CreateSCCMCollection
    objRecordset.MoveNext
Loop

Sub CreateSCCMCollection
Set newCollection = objSMS.Get("SMS_Collection").SpawnInstance_()

newCollection.Name = strColName
newCollection.OwnedByThisSite = True
path=newCollection.Put_

'the following two lines are used to obtain the CollectionID
'of the collection we just created
Set Collection=objSMS.Get(path)
strCollID= Collection.CollectionID
'now we create a relationship betwen the new collection
'and it's parent.

Set newCollectionRelation = objSMS.Get ( "SMS_CollectToSubCollect" ).SpawnInstance_()
newCollectionRelation.parentCollectionID = strParentID
newCollectionRelation.subCollectionID = strCollID
newCollectionRelation.Put_
End Sub

No comments: