Davegbuf Posted September 26, 2007 Share Posted September 26, 2007 Hello, I am having trouble with a line on a script which I am translating from a VBScript. The $CollectionRule = $gService.Get("SMS_$CollectionRuleDirect").SpawnInstance_() line to be more specific. The script adds a computer name to a Microsoft SMS collection. AutoIT doesn't seem to like the .SpawnInstance portion of the script. Below is the original VBScript and the AutoIT version which I am working on for your reference. I Trully appreciate any help. The VBScript version. This one works fine: ' ==================================================================================================== ' ************************************************************************* ' === Initialize Variables and Constants ' ************************************************************************* Option Explicit ' --- Force Declaration of variables ' === Script arguments override ==== ' These variables are for testing only. To test, assign values to the variables and then comment out ' the Comment-out the ValdateArguments()subrourtine. To restur, comment out the variables below, and ' uncomment the ValdateArguments() subroutine to allow original argument values to be passed to the script. 'TargetCollectionName = "#Test-AddUser" 'NewComputerName = "LT01385" ' ************************************************************************* ' == SMS Envronment Variables CONST SMSSiteCode = "BUA" ' --- SMS Server Central Site Code CONST SMSServer = "RPC3SMS01NT" ' --- SMS Server ' ------------------------------------------------------------- ' === Script varables DIM lLocator ' --- Object handle for WMI Scripting "Locator object" ? DIM gService ' --- Object hanlde for WMI object model ConnectServer object ? DIM ResID ' --- Store the SMS ResourceID for the desired resource DIM RuleName ' --- Name for Membership Rule (label seen in SMS collection properties) DIM AllComputersSet ' --- Object handle to store the query results of the SMS System_R_System table DIM AllComputersItem ' --- Index variable used for the AllComputersSet Object Collection (Array) DIM CollectionRule ' --- CollectionRule DIM oCollectionSet ' --- Object handle to store collection names from table SMS_Collection DIM CollListItem ' --- Index variable for Collection Object (Array) DIM WshShell ' --- Object handle for WshShell object (Windows Script Host Shell) DIM oFSO ' --- Object handle for the FSO (File System Object) DIM AddMembRuleSuccess ' --- Flag to track added collection membership rule status DIM LogFileHandle ' --- File handle for the log file Public TargetCollectionName ' --- Store command-line argument for desired collection name to add a computer resource Public NewComputerName ' --- Store command-line argument for desired computer resource to add to the collection ' === Script Environment ' -- Script Path Location DIM ScriptDir ' --- Store the current Script location Set oFSO = CreateObject("Scripting.FileSystemObject") ScriptDir = oFSO.GetAbsolutePathName(".") ' -- Script Logfile DIM LogFile LogFile = ScriptDir & "\AddComputer2Coll.log" ' --- Path Location and file name of the log file Const ForAppending = 8 ' --- Action to perform on Log file ( 8 = for appending text) ' ********************************************************************************************* ' ===== Connect to provider namespace for local computer. ' ********************************************************************************************* Set lLocator = CreateObject("WbemScripting.SWbemLocator") Set gService = lLocator.ConnectServer(SMSServer, "Root\SMS\Site_" & SMSSiteCode) ' -- /// FileSytemObject already instantiated in subroutine ScriptPath() into object handle oFSO ' ******************************************** ' ===== Script Start ======================= ' ******************************************** ValdateArguments() ' --- Load command-line arguments into variables ValidateComputerResource() ' --- Find computer name match in SMS "All Systems" table SMS_R_System FindCollandAddMembRule() ' --- Find specific collection and add membership rule to the collection UpdateLogFile() ' --- Update log file with results wscript.quit ' ************************************************************************************* ' ************************************************************************************* ' Subroutines ' ************************************************************************************* ' ************************************************************************************* ' ************************************************************************************* ' **** Validate command-line parameters and load them into variables to be used ' **** by the script. Otherwise, display an error message and exit the script ' ************************************************************************************* Sub ValdateArguments() ' --- Load command-line arguments into variables If wscript.arguments.count<> 2 Then wscript.echo "Two arguments please - The collection followed by Computer Name" wscript.quit ' --- quit if invalid number of arguments Else TargetCollectionName = wscript. arguments(0) NewComputerName = wscript. arguments(1) End if End Sub ' ************************************************************************** ' **** Search the SMS_R_System table for a match to the computer name passed by the ' **** command-line argument, then store the corresponding SMS ResourceID ' **** in a variable. ' ************************************************************************** Sub ValidateComputerResource() ' --- Find computer name match in SMS "All Systems" table SMS_R_System ' --- Create object with query results from the SMS SQL table SMS_R_System Set AllComputersSet = gService.ExecQuery("Select * From SMS_R_System WHERE Name LIKE ""%" + NewComputerName + "%""") ' --- Iterate through the SMS_R_System table resultset (loaded into the variable "AllComputersSet") ' and match the name to be added. Then retreive the ResourceID for the corresponding computer record. For Each AllComputersItem In AllComputersSet If UCase(AllComputersItem.Name) = UCase(NewComputerName) Then ResID = AllComputersItem.ResourceID RuleName = "ResourceID = " & ResID & " " & AllComputersItem.NetBiosName End If Next End Sub '*************************************************************************** '**** Walk through the the whole list of SMS collections and search for a match to the '**** desired collection. If the desired collection is sucessfully found, then '**** add the Membership rule created in the subrioutine CreateSMSDirectRule() to the '**** existing matched collection. '*************************************************************************** Sub FindCollandAddMembRule() ' --- Find specific collection and add membership rule to the collection ' --- Create object with query results from the SMS_Collection table Set oCollectionSet = gService.ExecQuery("Select * From SMS_Collection") AddMembRuleSuccess = "False" ' --- Initialize flag to indicate Added Collection Membership Rule Failed ' --- Walk through the list of SMS collections and find a match to the collection name passed by the ' command-line argument. If the collection exists, then add the new direct rule that includes ' the new computer name to the collection. For Each CollListItem In oCollectionSet If CollListItem.Name = TargetCollectionName Then '*************************************************************************** '**** Create a direct membership rule (spawn a blank instance) to add to an existing collection. '**** Then give that instance the values it needs - this is REQUIRED '*************************************************************************** Set CollectionRule = gService.Get("SMS_CollectionRuleDirect").SpawnInstance_() CollectionRule.ResourceClassName = "SMS_R_System" CollectionRule.RuleName = RuleName CollectionRule.ResourceID = ResID ' ***** Add the direct membership rule to matched collection. ************ CollListItem.AddMembershipRule CollectionRule If Err.Number = 0 Then ' --- If Error = 0, then adding membership was successful. AddMembRuleSuccess = "True" ' --- Set flag to "True" to indicate memb. rule added Successfully End If End If Next End Sub ####################################### The AutoIT Version is Here: ; ************************************************************************* ; === Initialize Variables and Constants ; ************************************************************************* AutoItSetOption('MustDeclareVars',1) ; --- Force Declaration of variables ; === Script arguments override ==== ; These variables are for testing only. To test, assign values to the variables and then comment out ; the Comment-out the ValdateArguments()subrourtine. To restur, comment out the variables below, and ; uncomment the ValdateArguments() subroutine to allow original argument values to be passed to the script. Global $TargetCollectionName = "#Test-AddUser" ; --- Store command-line argument for desired collection name to add a computer resource Global $NewComputerName = "DT00117" ; --- Store command-line argument for desired computer resource to add to the collection ; ************************************************************************* ; == SMS Envronment Variables CONST $SMSSiteCode = "BUA" ; --- SMS Server Central Site Code CONST $SMSServer = "RPC3SMS01NT" ; --- SMS Server ; ------------------------------------------------------------- ; === Script varables Global $lLocator ; --- Object handle for WMI Scripting "Locator object" ? Global $gService ; --- Object hanlde for WMI object model ConnectServer object ? Global $ResID ; --- Store the SMS ResourceID for the desired resource Global $RuleName ; --- Name for Membership Rule (label seen in SMS collection properties) Global $AllComputersSet ; --- Object handle to store the query results of the SMS System_R_System table Global $AllComputersItem ; --- Index variable used for the $AllComputersSet Object Collection (Array) Global $CollectionRule ; --- Store new Collection Rule Global $oCollectionSet ; --- Object handle to store collection names from table SMS_Collection Global $CollListItem ; --- Index variable for Collection Object (Array) Global $WshShell ; --- Object handle for $WshShell object (Windows Script Host Shell) Global $oFSO ; --- Object handle for the FSO (File System Object) Global $AddMembRuleSuccess ; --- Flag to track added collection membership rule status Global $LogFileHandle ; --- File handle for the log file ; === Script Environment ; -- Script Logfile Global $LogFile = "AddComputer2Coll.log" ; --- Path Location and file name of the log file Global $LogfilePath = @ScriptDir & '\Logs' ;Const ForAppending = 8 ; --- Action to perform on Log file ( 8 = for appending text) ; ********************************************************************************************* ; ===== Connect to provider namespace for local computer. ; ********************************************************************************************* Global $lLocator = ObjCreate("WbemScripting.SWbemLocator") Global $gService = $lLocator.ConnectServer($SMSServer, "Root\SMS\Site_" & $SMSSiteCode) ; ******************************************** ; ===== Script Start ======================= ; ******************************************** Initiate_Logfile() ; ------- Create a Log File to report script execution progress ; ValdateArguments() ; --- Load command-line arguments into variables ValidateComputerResource() ; --- Find computer name match in SMS "All Systems" table SMS_R_System FindCollandAddMembRule() ; --- Find specific collection and add membership rule to the collection UpdateLogFile() ; --- Update log file with results Exit ; ************************************************************************************* ; ************************************************************************************* ; Subroutines ; ************************************************************************************* ; ************************************************************************************* ; ************************************************************************************* ; **** Validate command-line parameters and load them into variables to be used ; **** by the script. Otherwise, display an error message and exit the script ; ************************************************************************************* #cs Func ValdateArguments() ; --- Load command-line arguments into variables If wscript.arguments.count<> 2 Then wscript.echo "Two arguments please - The collection followed by Computer Name" wscript.quit ; --- quit if invalid number of arguments Else $TargetCollectionName = wscript. arguments(0) NewComputerName = wscript. arguments(1) EndIf EndFunc #ce ; ************************************************************************** ; **** Search the SMS_R_System table for a match to the computer name passed by the ; **** command-line argument, then store the corresponding SMS ResourceID ; **** in a variable. ; ************************************************************************** Func ValidateComputerResource() ; --- Find computer name match in SMS "All Systems" table SMS_R_System ; --- Create object with query results from the SMS SQL table SMS_R_System $AllComputersSet = $gService.ExecQuery("Select * From SMS_R_System WHERE Name LIKE ""%" + $NewComputerName + "%""") ; --- Iterate through the SMS_R_System table resultset (loaded into the variable "$AllComputersSet") ; and match the name to be added. Then retreive the ResourceID for the corresponding computer record. For $AllComputersItem In $AllComputersSet If StringUpper($AllComputersItem.Name) = StringUpper($NewComputerName) Then $ResID = $AllComputersItem.ResourceID $RuleName = "ResourceID = " & $ResID & " " & $AllComputersItem.NetBiosName EndIf Next EndFunc ;*************************************************************************** ;**** Walk through the the whole list of SMS collections and search for a match to the ;**** desired collection. If the desired collection is sucessfully found, then ;**** add the Membership rule created in the subrioutine CreateSMSDirectRule() to the ;**** existing matched collection. ;*************************************************************************** Func FindCollandAddMembRule() ; --- Find specific collection and add membership rule to the collection ; --- Create object with query results from the SMS_Collection table $oCollectionSet = $gService.ExecQuery("Select * From SMS_Collection") $AddMembRuleSuccess = "False" ; --- Initialize flag to indicate Added Collection Membership Rule Failed ; --- Walk through the list of SMS collections and find a match to the collection name passed by the ; command-line argument. If the collection exists, then add the new direct rule that includes ; the new computer name to the collection. For $CollListItem In $oCollectionSet If $CollListItem.Name = $TargetCollectionName Then ;*************************************************************************** ;**** Create a direct membership rule (spawn a blank instance) to add to an existing collection. ;**** Then give that instance the values it needs - this is REQUIRED ;*************************************************************************** ;$objInParam = $objService.Methods_("Create").inParameters.SpawnInstance_() $CollectionRule = $gService.Get("SMS_$CollectionRuleDirect").SpawnInstance_() $CollectionRule.ResourceClassName = "SMS_R_System" $CollectionRule.RuleName = $RuleName $CollectionRule.ResourceID = $ResID ; ***** Add the direct membership rule to matched collection. ************ $CollListItem.AddMembershipRule = $CollectionRule If @error = 0 Then ; --- If @Error = 0, then adding membership was successful. $AddMembRuleSuccess = "True" ; --- Set flag to "True" to indicate memb. rule added Successfully EndIf EndIf Next EndFunc ;*************************************************************************** ;**** Update log file below with success/Failure message. ;*************************************************************************** Func UpdateLogFile() ; --- Update log file with results If $AddMembRuleSuccess = "True" Then ; --- Append status message _FileWriteLog($LogFileHandle,$LogFileHandle.WriteLine & $NewComputerName & " was added successfully.") Else _FileWriteLog($LogFileHandle,$LogFileHandle.WriteLine & $NewComputerName & " was NOT added successfully.") EndIf FileClose($LogFileHandle) ; --- Close Log file object EndFunc ; ==================================================================================================== === #cs Function Description: Check for directory existence, create directory, and create log file Function Usage: Create local execution log file to record installation progress Parameters: None Results Returned: None ; --------------------------------------------------------------------------------------- #ce Func Initiate_Logfile() ; ------- Create a Log File to report script execution progress If Not FileExists($LogfilePath) Then DirCreate($LogfilePath) ; Create Logfile directory if not exists $LogFileHandle = $LogfilePath & '\' & $LogFile ; Execution Log file full path _FileWriteLog($LogFileHandle,'') ; --- Add a blank line _FileWriteLog($LogFileHandle,'Initiated by : ' & @UserName) _FileWriteLog($LogFileHandle,'******************************************') EndFunc ; ==================================================================================================== === ; ===================================================================================== ; ==================================================================================================== === ; ============================ AutoIT or 3rd Party User Defined Functions ============================= ; ==================================================================================================== === #cs Function Description: Create directory and execution log file Function Usage: Create directory and execution log file Parameters: None Results Returned: None ; --------------------------------------------------------------------------------------- #ce ;=============================================================================== ; ; Description: Writes the specified text to a log file. ; Syntax: _FileWriteLog( $sLogPath, $sLogMsg ) ; Parameter(s): $sLogPath - Path and filename to the log file ; $sLogMsg - Message to be written to the log file ; Requirement(s): None ; Return Value(s): On Success - Returns 1 ; On Failure - Returns 0 and sets: ; @error = 1: Error opening specified file ; @error = 2: File could not be written to ; Author(s): Jeremy Landes <jlandes at landeserve dot com> ; Note(s): If the text to be appended does NOT end in @CR or @LF then ; a DOS linefeed (@CRLF) will be automatically added. ; ;=============================================================================== Func _FileWriteLog($sLogPath, $sLogMsg) ;============================================== ; Local Constant/Variable Declaration Section ;============================================== Local $sDateNow Local $sTimeNow Local $sMsg Local $hOpenFile Local $hWriteFile $sDateNow = @YEAR & "-" & @MON & "-" & @MDAY $sTimeNow = @HOUR & ":" & @MIN & ":" & @SEC $sMsg = $sDateNow & " " & $sTimeNow & " : " & $sLogMsg $hOpenFile = FileOpen($sLogPath, 1) If $hOpenFile = -1 Then SetError(1) Return 0 EndIf $hWriteFile = FileWriteLine($hOpenFile, $sMsg) If $hWriteFile = -1 Then SetError(2) Return 0 EndIf FileClose($hOpenFile) Return 1 EndFunc ;==>_FileWriteLog ;======================================== Link to comment Share on other sites More sharing options...
PsaltyDS Posted September 26, 2007 Share Posted September 26, 2007 You are putting a variable name inside quotes: $CollectionRule = $gService.Get("SMS_" & $CollectionRuleDirect).SpawnInstance_()oÝ÷ Øí«]¡ë'ßÛ]¢+m¯&ëy©"º§¶-zºÚ"µÍÌÍÐÛÛXÝ[Û[HH ÌÍÙÔÙXÙKÙ] ][ÝÔÓT×É][ÝÈ [È ÌÍÐÛÛXÝ[Û[QXÝ BÌÍÓ]Ò[Ý[ÙHH ÌÍÐÛÛXÝ[Û[KÜ]Û[Ý[ÙWÊ Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law Link to comment Share on other sites More sharing options...
Davegbuf Posted October 2, 2007 Author Share Posted October 2, 2007 You are putting a variable name inside quotes: $CollectionRule = $gService.Get("SMS_" & $CollectionRuleDirect).SpawnInstance_()oÝ÷ Øí«]¡ë'ßÛ]¢+m¯&ëy©"º§¶-zºÚ"µÍÌÍÐÛÛXÝ[Û[HH ÌÍÙÔÙXÙKÙ] ][ÝÔÓT×É][ÝÈ [È ÌÍÐÛÛXÝ[Û[QXÝ BÌÍÓ]Ò[Ý[ÙHH ÌÍÐÛÛXÝ[Û[KÜ]Û[Ý[ÙWÊ Thank You PsaltyDS. After hours of working on the project, the last thing I should have done was a global replace before going home. The problem was there in my face all along. I appreciate your help very much. Link to comment Share on other sites More sharing options...
martin Posted October 2, 2007 Share Posted October 2, 2007 Off subject but I'm thinking of starting a campaign to stop people using the Autoit tags to wrap their code in. Look at the mess it makes, and this problem has been going on for a long time. Using code instead doesn't seem to cause a problem and it formats the code fine so why bother with the AutoIt tags? There may be a reason that I don't appreciate, but when it garbles things then it can't be sensible to use it. Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now