2014年7月4日 星期五

WMI First using sample:Method 1: To connect to WMI using SWbemLocator--- Creating a Registry Key Using VBScript

You can use the methods of the SWbemLocator object to obtain an SWbemServices object that represents a connection to a namespace on either a local computer or a remote host computer. You can then use the methods of the SWbemServices object to access WMI.
You can use the methods of an SWbemServices object to perform operations against a namespace on either a local host or a remote host. This object cannot be created by the VBScript CreateObject call.

Step 1write the vb script as following, and save it as "NEW_RegistryKey.vbs"


HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strSubkeyname = "SOFTWARE\MyKey\MySubKey"
strValueName=" MyValueName"
strValue=" MyValue"

''''''' 1Retrieve a locator object with a call to CreateObject.
Set objLocator = CreateObject("WbemScripting.SWbemLocator")

'''''''2 Log on to the namespace using a call to the ConnectServer method.
'''''''Name space can set "root\cimv2" or "root\ default "
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objService = objLocator.ConnectServer(".", "root\cimv2")
'''''''NOTEIf you do not specify a computer in the call to ConnectServer, then WMI
'''''''connects to the local computer.
'''''''If you do not specify a namespace, then WMI connects to the namespace specified in
'''''''the registry key:
'''''''HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting\Default Namespace
'''''''The default namespace is \root\cimv2.

'''''''3Set the impersonation level with a call to the SWbemServices.Security_ method.
objService.Security_.ImpersonationLevel = 3

'''''''4Implement the purpose of your script (add new registry key).
' Use Get TO GET THE CLASS StdRegProv; Use ExecMethod to call the method CreateKey
Set objStdRegProv = objService.Get("StdRegProv")
Set Inparams = objStdRegProv.Methods_("CreateKey").Inparameters
Inparams.Hdefkey = HKEY_LOCAL_MACHINE
Inparams.Ssubkeyname = strSubkeyname
set Return = objStdRegProv.ExecMethod_("CreateKey", Inparams)

'Show output parameters object and the registry value HKLM\SOFTWARE\
WScript.Echo Return.GetObjectText_

If Return.ReturnValue <> 0 Then
    WScript.Echo "The operation failed." & VBCRLF _
        & "ReturnValue:" &[Integer(FOutParams.ReturnValue)] 
    WScript.Quit
Else
    wScript.Echo "New registry key created" & VBCRLF _
        & strSubkeyname
End If

''''''' add new registry key's ValueName and value
Set Inparams = objStdRegProv.Methods_("SetStringValue").Inparameters
Inparams.Hdefkey = HKEY_LOCAL_MACHINE
Inparams.Ssubkeyname = strSubkeyname
Inparams.sValueName = strValueName
Inparams.sValue = strValue
set Return = objStdRegProv.ExecMethod_("SetStringValue", Inparams)

Step 2using cscript to run NEW_RegistryKey.vbs"on windows command prompt



Step 3To check the result on registry setting


沒有留言:

張貼留言