vbscript to add machine names to SMS collection (Full Version)

All Forums >> [Management Products] >> Microsoft Systems Management Server >> SMS 2003



Message


lnesta431 -> vbscript to add machine names to SMS collection (8/17/2006 5:30:49 AM)

Guys,

I discovered this excellent script of Michael to add Machines into a collection.
Only problem is that the script is creating each time the collection once again.

So If I run the script a second time to update the membership of  the collection, the script is creating
once again a new collection and adds the members into this collection.

I would like that the script is only adding the members without creating  a new collection each time.

Can someone help me with this? Many Tnx




' *********************************************************************************
' File:         MAKECOLL.vbs
' Version:      1.1
' Author:       Michael Niehaus
' *********************************************************************************

' The following script is very similar to the MAKECOLL C++ example Microsoft
' provides in the Platform SDK.  The main differences:
'   1. This is readable VBScript, not C++/COM gibberish.
'   2. This doesn't include logic to pass in parameters.  Instead, edit the
'      constants below.
'   3. No error handling.  It clutters up the code.
' Questions or problems?  Contact me at "niehaus@mac.com".  Thanks.


' *********************************************************************************
' Initialization
' *********************************************************************************

' Constants - change as appropriate

server = "testlabsmserver"       ' Server name of the SMS site server
user = "common\administrator"                        ' Optional user ID
password = "password"                    ' Optional password
gbIPAddress = false              ' False = file contains machine names; true = file contains IP addresses
fileName = "test.txt"         ' File containing the list of machines.
collectionName = "Test1"       ' Collection name
parentCollectionID = "COLLROOT"  ' Change this if you want to make a subcollection

' *********************************************************************************
' Main code
' *********************************************************************************

' Call the "Init" function to connect to SMS.  This returns the "services" object.
Init services, server, user, password

' Create the collection given the collection name and the services object.  This
' returns the collection path.
CreateCollection services, collectionName, collectionPath

' Associate the collection with its parent.  Without this step, the collection
' would be orphaned, as you wouldn't be able to see it in the SMS Administrator
' (although it would still exist).
CreateCollectToSubCollect services, collectionPath
    
' Process the file containing the list of machine names or IP addresses.  This
' function will then call all the other functions needed to create membership
' rules, add them to SMS, then refresh the collection.   
ProcessListFile services, fileName, collectionPath
       
' Done.

   
' *********************************************************************************
' Subroutines
' *********************************************************************************

Sub Init(services, server, user, password)

    On Error Resume Next

    ' Connect to the "root\sms" namespace on the specified server to locate the SMS provider,
    ' using the provided server name, user ID and password.
    Set locator = CreateObject("WbemScripting.SWbemLocator")
    Set tempServices = locator.ConnectServer(server,"root\sms",user,password)
    If Err then
        CheckError
        Exit Sub
    End if

    ' Now figure out the site code for this server.
    Set result = tempServices.ExecQuery("SELECT * FROM SMS_ProviderLocation WHERE ProviderForLocalSite=true")
    For each r in result
        providerServer = r.Machine
        namespace = Mid(r.NamespacePath,InStr(3,r.NamespacePath,"\")+1)
    Next
    Set tempServices = Nothing

    ' Finally, connect to the true provider location.
    Set services = locator.ConnectServer(providerServer,namespace,user,password)
    If Err then
        CheckError
        Exit Sub
    End if

    ' We could set context values at this point, but for what we're doing it isn't worth the effort.
    ' The Platform SDK sample sets the application name and machine name, which would be seen
    ' in the SMS provider log (SMSPROV.LOG) and any status messages generated as a result of this
    ' code.

End Sub

Sub CreateCollection(services, collectionName, collectionPath)

    On Error Resume Next

    ' Spawn an instance of SMS_Collection
    Set collection = services.Get("SMS_Collection").SpawnInstance_()       
    If Err then
        CheckError
        Exit Sub
    End if

    ' Store the collection name in the collection instance
    collection.Name = collectionName

    ' Store the OwnedByThisSite value in the collection instance
    collection.OwnedByThisSite = true

    ' Store the collection instance itself in the database.
    Set pathObj = collection.Put_
    If Err then
        CheckError
        Exit Sub
    End if

    ' Get the collection ID
    collectionPath = pathObj.Path

End Sub

Sub CreateCollectToSubCollect(services, collectionPath)

    On Error Resume Next

    ' Easy way: retrieve the collection to get its collection ID, instead of
    ' parsing the path
    Set collection = services.Get(collectionPath)
    If Err then
        CheckError
        Exit Sub
    End if
    collectionID = collection.CollectionID

    ' Spawn an instance of SMS_CollectToSubCollect
    Set association = services.Get("SMS_CollectToSubCollect").SpawnInstance_()
    If Err then
        CheckError
        Exit Sub
    End if
   
    ' Store the collection ID
    association.subCollectionID = collectionID

    ' Store the parent ID
        association.parentCollectionID = parentCollectionID

    ' Store the association instance itself
    association.Put_
    If Err then
        CheckError
        Exit Sub
    End if

End Sub

Sub GetResourceIDForNetbiosName(services, netbiosName, resourceID)

    On Error Resume Next
   
    ' Build Query string.
    query = "SELECT ResourceId FROM SMS_R_System WHERE NetbiosName = """ & netbiosName & """"
   
    ' Execute the query
    Set result = services.ExecQuery(query)
    If Err then
        CheckError
        Exit Sub
    End if
   
    ' Walk through the elements of the enumerator.
    ' Assume there will only be 1 computer with the requested name, if any.
    resourceID = 0  ' Assume the worst
    For each r in result
        resourceID = r.ResourceID
    Next

End Sub


Sub GetResourceIDForIPAddress(services, IPAddress, resourceID, netbiosName)

    On Error Resume Next

    ' Build Query string.
    query = "SELECT ResourceId FROM SMS_R_System WHERE IPAddresses = """ & IPAddress & """"

    ' Execute the query
    Set result = services.ExecQuery(query)
    If Err then
        CheckError
        Exit Sub
    End if
   
    ' Walk through the elements of the enumerator.
    ' Assume there will only be 1 computer with the requested name, if any.
    resourceID = 0  ' Assume the worst
    For each r in result
        resourceID = r.ResourceID
        netbiosName = r.NetbiosName
    Next

End Sub

Sub AddMembershipRule(services, rules, resourceID, netbiosName)

    On Error Resume Next

    ' Spawn an instance of a direct collection rule.
    Set rule = services.Get("SMS_CollectionRuleDirect")
    If Err then
        CheckError
        Exit Sub
    End if
   
    ' Store the resource class name (sms_r_system)
    rule.ResourceClassName = "SMS_R_System"

    ' Build a rule name
    rulename = netbiosName
   
    ' Store the rule name
    rule.RuleName = rulename
   
    ' Store ResourceID
    rule.ResourceID = resourceID

    ' Add it to the collection
    rules.Add rulename, rule

End Sub

Sub AddCollectionMembershipRules(services, collectionPath, rules)

    On Error Resume Next

    ' Get the collection
    Set collection = services.Get(collectionPath)
    If Err then
        CheckError
        Exit Sub
    End if

    ' Add the membership rules
    collection.AddMembershipRules rules.Items
    If Err then
        CheckError
        Exit Sub
    End if

End Sub

Sub UpdateCollectionMembership(services, collectionPath)

    On Error Resume Next

    ' Get the collection
    Set collection = services.Get(collectionPath)
    If Err then
        CheckError
        Exit Sub
    End if

    ' Request the refresh (without subcollections; change to true if you want those)
    collection.RequestRefresh false

End Sub


Sub ProcessListFile(services, filename, collectionPath)

    ' Build a dictionary object to hold the rules.  We'll use this as a dynamically-
    ' sized array.
    Set rules = CreateObject("Scripting.Dictionary")

    ' Open the file
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set listFile = fs.OpenTextFile(fileName)
   
    ' Read the file
    While not listFile.AtEndOfStream

        ' Get a line from the file
        line = listFile.ReadLine
           
        count = count + 1
           
        ' Call the appropriate GetResourceID function
        If gbIPAddress then
            GetResourceIDForIPAddress services, line, resourceID, netbiosName
        Else
            netbiosName = line
            GetResourceIDForNetbiosName services, netbiosName, resourceID
        End if

        ' Add a rule
        If resourceID > 0 then
            AddMembershipRule services, rules, resourceID, netbiosName
        Else
            WScript.Echo line & " not found on SMS_R_System table"
        End if       
    WEnd
   
    ' Add all the rules to the collection
    AddCollectionMembershipRules services,collectionPath,rules
   
    ' Update the collection (this should be automatic, but it shouldn't hurt to tell SMS again)
    UpdateCollectionMembership services, collectionPath
   
End Sub

Sub CheckError
    WScript.Echo "An error occurred: " & Err.Description & " (" & Err.Number & ")"
    Set lastError = CreateObject("WbemScripting.SWbemLastError")
    WScript.Echo "WMI error details:"
    For each p in lastError.Properties_
        WScript.Echo "    " & p.Name & " = " & p.Value
    Next
End Sub
 




eschloss -> RE: vbscript to add machine names to SMS collection (8/17/2006 8:12:57 AM)

The script you are using is called MakeColl.vbs, it makes a collection.  There is a subrouting called CreateCollection.  You can either modify the script so it doesn't call the routine, or use this script from Mark Nunn.

'#################################################################
'#colladd.vbs                                                                                                             #
'#                                                                                                                              #
'#This adds a list of machine names from a file to a collection.                                     #
'#It can also list all collections on a server.                                                                  #
'#################################################################
'#M.Nunn 03/06/03                                                                                                  #
'#################################################################

Set fso = CreateObject("Scripting.FileSystemObject")     
Set arrArgs = WScript.Arguments
if (arrArgs.Count = 0) Then        'Display Blurb
wscript.echo ("Colladd.vbs v1.0")     
wscript.echo ("03/06/03 Mark Nunn")
wscript.echo ("Colladd.vbs server filename collectionID - to add from file to collection")
wscript.echo ("Colladd.vbs server - to list collectionID's")
else
on error resume next        'Some error handling
strServer=arrArgs(0)        'set variables from command line
if (arrArgs.Count = 3) Then
 strFile=arrArgs(1)
 strCollID=arrArgs(2)
end if
Set objLocator = CreateObject("WbemScripting.SWbemLocator")    
Set objSMS = objLocator.ConnectServer(strServer, "Root/SMS")   'connect to sms
objSMS.Security_.ImpersonationLevel = 3
wscript.Echo("Connecting to Root/SMS on " & strServer)   

set colSiteDetails=objSMS.ExecQuery("select Machine, SiteCode from SMS_ProviderLocation where ProviderForLocalSite=True")
For Each insSiteDetails In colSiteDetails
 strSiteCode=insSiteDetails.SiteCode
next          
wscript.Echo("Connecting to Root/SMS/site_" & strSiteCode &" on " & strServer)
set objSMS=objLocator.ConnectServer(strServer, "root/SMS/site_" + strSiteCode)
wscript.Echo("Connected")
if (arrArgs.Count < 3) Then       'if not all arguments supplied list colelctions
 set colCollections=objSMS.ExecQuery("select CollectionID, Name from SMS_Collection ORDER BY CollectionID")
 wscript.echo("CollectionID" & vbTab & "Name")
 For Each insCollection In colCollections
  wscript.echo(insCollection.CollectionID & VbTab & insCollection.Name)
 Next
else          'otherwise add from file
 set instColl = objSMS.Get("SMS_Collection.CollectionID="&"""" & strCollID & """")
 if Instcoll.Name="" then      'check valid collection
  wscript.echo (strCollId &" Not Found")
 else
  Set filNames = fso.OpenTextFile(strFile)    'open file of machines
  if  (filNames) then
   While not filNames.AtEndOfStream
    strMachine=filNames.ReadLine    'read each line and find resource ID
    set colNewResources=objSMS.ExecQuery("SELECT ResourceId FROM SMS_R_System WHERE NetbiosName ='" & strMachine & "'") 
    strNewResourceID = 0      
    For each insNewResource in colNewResources
     strNewResourceID = insNewResource.ResourceID
    Next
    if strNewResourceID <> 0 then    'if one exists crate a collection rule
     Set instDirectRule = objSMS.Get("SMS_CollectionRuleDirect").SpawnInstance_ ()
     instDirectRule.ResourceClassName = "SMS_R_System" 
     instDirectRule.ResourceID = strNewResourceID
     instDirectRule.RuleName = strMachine & " - colladd"
     instColl.AddMembershipRule instDirectRule , SMSContext
     instColl.RequestRefresh False
     wscript.echo(strMachine & " Added to " & Instcoll.Name)
    else
     wscript.echo(strMachine & " Not Found")  'otherwise display error
    end if
   WEnd        'next line
  else
    wscript.echo ("Can't Open " & strfile)    'if file not found
  end if
 end if
end if
end if




lnesta431 -> RE: vbscript to add machine names to SMS collection (8/17/2006 9:19:50 AM)

OK thanks! I will give it a try but what do I have to do with following syntax:

strServer=arrArgs(0)
if (arrArgs.Count = 3) Then
strFile=arrArgs(1)
strCollID=arrArgs(2)

I suppose I have to declare here my variables?
ex.: strserver = "testlabsmsserver"

Is this correct? Sorry formy ignorance but I'm not a vb guru.







pstreck -> RE: vbscript to add machine names to SMS collection (8/17/2006 10:16:57 AM)

That code references the arrArgs array which was set to WScript.Arguments a couple lines above that:

Set arrArgs = WScript.Arguments

WScript.Arguments is a collection of command line options passed to the script. For instance when you call "cscript.exe scriptname.vbs test" the string test is the first argument in the WScript.Arguments collection. For more information check out:

http://msdn2.microsoft.com/en-us/library/z2b05k8s.aspx





eschloss -> RE: vbscript to add machine names to SMS collection (8/17/2006 11:05:36 AM)

you have to run this from the command line:
cscript.exe colladd.vbs SMSSiteServer ListOfPCs.txt CollectionID

where:
SMSSiteServer is the name of the SMS site server
ListOfPCs.txt is a text file with a list of machines, one per line
CollectionID is the collection ID of the collection you want to add the machines to.




lnesta431 -> RE: vbscript to add machine names to SMS collection (8/18/2006 3:19:51 AM)

Tnx mate! I owe you a rate!!




ssamannan -> RE: vbscript to add machine names to SMS collection (6/27/2008 11:10:14 AM)

Thank you .Excellent script.




pglyn-williams -> RE: vbscript to add machine names to SMS collection (8/5/2008 4:07:21 PM)

Thanks for the scripts folks.




Page: [1]

Valid CSS!




Forum Software © ASPPlayground.NET Advanced Edition 2.4.5 ANSI
0.328125