Writing WMI Scripts in JScript

The example scripts shown for the Scripting API for WMI are written in VBScript. If you use these examples as models for scripts written in Microsoft JScript, you must take into account several differences between these languages.

The following example scripts show the VBScript for the Scripting API for WMI and how to write comparable scripts using JScript:

  • New object creation in JScript is done using "new ActiveXObject" rather than the CreateObject function used in VBScript.

    The following VBScript code example creates a new SWbemLocator object.

    Set oLoc = CreateObject("WbemScripting.SWbemLocator")

    The following JScript code example also creates a new SWbemLocator object.

    oLoc = new ActiveXObject("WbemScripting.SWbemLocator");
  • Error handling in JScript is accomplished with try and catch blocks rather than the VBScript "on error" construction.

    You also can obtain supplemental information about errors with data from a WMI SWbemLastError object, if supported by the provider. The VBScript and JScript examples at the end of this topic demonstrate this difference.

    The following VBScript example shows the line of code that must be included at the beginning of a script to obtain supplemental information about errors.

    On Error Resume Next

    A call to the user-defined CheckResult subroutine is made whenever the return value of an operation must be checked. To determine that a method call succeeded, you must check the return value, because no exception is thrown for the method itself if the provider successfully accepts the method call.

    The JScript version places the script operations in a try block and handles errors in a catch(err) block.

  • Methods in VBScript can be called directly, while JScript methods are called with the SWbemMethod, InParam, and OutParam objects.

    The following VBScript code example shows how to call the StdRegProv.GetMultiStringValue method.

    E = oReg.GetMultiStringValue(HKLM, RegPath, "Sources", sValues)

    To make this call in JScript, you must call SWbemMethodSet.Item to set up the name of the method ("GetMultiStringValue") and call SWbemObject.SpawnInstance_to create an instance of an InParam object. Then you define the InParam object parameter values.

    The following JScript code example sets a value for the first parameter of the GetMultiStringValue method.

    oInParam.hDefKey = HKLM;

    The following JScript code example that calls SWbemObject.ExecMethod_ actually executes the StdRegProv.GetMultiStringValue method, with the InParam object supplying the parameter for GetMultiStringValue.

    oOutParam = oReg.ExecMethod_(oMethod.Name, oInParam);

    The OutParam object now contains the result of the GetMultiStringValue operation.

    For more information about setting up an InParam object, see SWbemServices.ExecMethod.

    For most WMI methods an OutParam object only contains the return value for the operation. The StdRegProv object, however, has methods which return the contents of the registry.

    Note that the SWbemMethod calling procedure can also be used in VBScript, but is not necessary because calls to WMI methods work like calls to VBScript functions.

  • Array handling in VBScript differs from JScript.

    Arrays in VBScript are safearrays. The returned array can be accessed directly by VBScript, using the LBound and UBound functions.

    The following VBScript code example shows how to use the LBound and UBound functions to access arrays.

    For i = LBound(sValues) To UBound(sValues)
        WScript.Echo "KeyName: " & sValues(i)

    The following JScript code example accesses arrays by using the toArray() method to convert the WMI safearray to an array that is recognized by the JScript engine.

    aNames = oOutParam.sValue.toArray();
  • JScript, unlike VBScript, requires that backslashes (\) be escaped. This affects WMI paths, registry paths, and file paths.

    The following VBScript code example shows how to write the path .

    strRegistryPath = "SOFTWARE\Microsoft\Office"

    The following JScript code example also writes the path.

    strRegistryPath = "SOFTWARE\\Microsoft\\Office";

    For more information, see Describing the Location of a WMI Object.

     You should also check the return value of the method call to see if it succeeded (an exception is not thrown if the provider successfully accepted the method call):    strKeyPath = "SOFTWARE\\Microsoft\\GOOD";   ret = objReg.CreateKey(HKEY_LOCAL_MACHINE,strKeyPath); WScript.Echo("Method returned : " + ret);

Note  WMI does not accept JScript sparse arrays as input parameters. All the elements in an array passed to a WMI method must have values or an error is likely to occur.

VBScript Version

The following code example is shown in both VBScript and JScript. Both scripts display all keys under SYSTEM\CurrentControlSet\Services\Eventlog\System, with Names and Types. Then the scripts get and display the value of the \Sources registry value, which has a data type of REG_MULTI_SZ.

Note that \Sources is the named value mentioned in the GetMultiStringValue Method in Class StdRegProv. These scripts execute on computer systems running Windows 2000 and Windows XP.

On Error Resume Next

Dim oLoc, oSvc, oReg
Dim i
Dim sNames()
Dim aTypes()

Dim sRegTypes
sRegTypes = Array(_
    "                              ", _
    "REG_SZ                        ", _
    "REG_EXPAND_SZ                 ", _
    "REG_BINARY                    ", _
    "REG_DWORD                     ", _
    "REG_DWORD_BIG_ENDIAN          ", _
    "REG_LINK                      ", _
    "REG_MULTI_SZ                  ", _
    "REG_RESOURCE_LIST             ", _
    "REG_QWORD                     ")

Const HKLM = &H80000002 

' The registry path to the keys of interest
Const RegPath = _

Set oLoc = CreateObject("WbemScripting.SWbemLocator")
Set oSvc = oLoc.ConnectServer("", "root\default")

' Passes the VBScript Err object to the user-defined
' subroutine to check the return code.
Call CheckResult("ConnectServer", err)                '

' Obtains a registry provider object
Set oReg = oSvc.Get("StdRegProv")            
Call CheckResult("Get StdRegProv", err)
E = oReg.EnumValues(HKLM, RegPath, sNames, aTypes)
Call CheckResult("EnumValues", err)

' List the names and types in the registry path
For i = LBound(aTypes) To UBound(aTypes)
    WScript.Echo "Type: " & sRegTypes(aTypes(i)) _
        & " KeyName: " & sNames(i)

' Obtains and displays all the strings in the multistring value
E = oReg.GetMultiStringValue(HKLM, RegPath, "Sources", sValues)
Call CheckResult("GetMultiStringValue", err)

For i = LBound(sValues) To UBound(sValues)
    WScript.Echo "KeyName: " & sValues(i)

'User-defined function to check the result of the operation
function CheckResult(ByRef msg, ByRef error)
    If error <> 0 Then
        WScript.Echo "Error occurred in " & msg
        WScript.Echo "Code " & Hex(error) _
            & "; Description: " & error.description
    End if
End function

JScript Version

sRegTypes = new Array(
    "                              ",    // 0
    "REG_SZ                        ",    // 1
    "REG_EXPAND_SZ                 ",    // 2
    "REG_BINARY                    ",    // 3
    "REG_DWORD                     ",    // 4
    "REG_DWORD_BIG_ENDIAN          ",    // 5
    "REG_LINK                      ",    // 6
    "REG_MULTI_SZ                  ",    // 7
    "REG_RESOURCE_LIST             ",    // 8
    "REG_QWORD                    ");    // 11

HKLM = 0x80000002;
sRegPath = "SYSTEM\\CurrentControlSet\\Services\\Eventlog\\System";

    // VBScript: Set oLoc = CreateObject("WbemScripting.SWbemLocator")
    // JScript:
    oLoc = new ActiveXObject("WbemScripting.SWbemLocator");

    // VBScript: Set oSvc = oLoc.ConnectServer(null, "root/default")
    // JScript:
    oSvc = oLoc.ConnectServer(null, "root\\default");
    // VBScript: Set oReg = oSvc.Get("StdRegProv")
    // JScript:
    oReg = oSvc.Get("StdRegProv");

    // VBScript: E = oReg.EnumValues(HKLM, RegPath, sNames, aTypes)
    // JScript:
    oMethod = oReg.Methods_.Item("EnumValues");
    oInParam = oMethod.InParameters.SpawnInstance_();
    oInParam.hDefKey = HKLM;
    oInParam.sSubKeyName = sRegPath;
    oOutParam = oReg.ExecMethod_(oMethod.Name, oInParam);
    aNames = oOutParam.sNames.toArray();
    aTypes = oOutParam.Types.toArray();

    for (i = 0; i < aNames.length; i++)
        WScript.Echo("Type: ", sRegTypes[aTypes[i]],
            " KeyName: ", aNames[i]);
    // VBScript: E = oReg.GetMultiStringValue( _
    //     HKLM, RegPath, "Sources", sValues)
    // JSCript:
    oMethod = oReg.Methods_.Item("GetMultiStringValue");
    oInParam = oMethod.InParameters.SpawnInstance_();
    oInParam.hDefKey = HKLM;
    oInParam.sSubKeyName = sRegPath;
    oInParam.sValueName = "Sources";
    oOutParam = oReg.ExecMethod_(oMethod.Name, oInParam);
    aNames = oOutParam.sValue.toArray();

    for (i = 0; i < aNames.length; i++)
        WScript.Echo("KeyName: ", aNames[i]);
    WScript.Echo("Error occurred\nCode: " + hex(err.number) + 
                          "Description: " + err.description);

//User-defined function to format error codes. 
//VBScript has a Hex() function but JScript does not.
function hex(nmb)
    if (nmb > 0)
        return nmb.toString(16);
        return (nmb + 0x100000000).toString(16);

See Also

Scripting in WMI

Using the WMI Scripting Type Library

System Registry Provider






Send comments about this topic to Microsoft

Build date: 5/4/2010