HomePage > Scripts > WMI in VBscript

WMI in VBscript

Tags:  

Sooner or later you'll probably need some WMI in a VBscript. A great number of the examples you will find on the web take this form:
  1. strComputer = "."
  2. Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  3. Set colResult = oWMI.ExecQuery("Select * from Win32_Battery")
  4. For Each oItem in colResult
  5.   Wscript.Echo "Availability: " & oItem.Availability
  6.   Wscript.Echo "Battery Status: " & oItem.BatteryStatus
  7.   '...many more lines like the one above...
  8. Next
And that's great - if you already know the exact properties you want. You can certainly look them up, in the WMI Reference. But here's another way to do it:
  1. strComputer = "."
  2. Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  3. Set colResult = oWMI.ExecQuery("Select * from Win32_Battery")
  4. For Each oItem in colResult
  5.   Set colProps = oItem.Properties_
  6.   For Each oProp in colProps
  7.     If oProp.IsArray = TRUE Then
  8.       wscript.echo oProp.Name & " = <ARRAY VALUE NOT DISPLAYED>"
  9.     Else
  10.       wscript.echo oProp.Name & " = " & oProp.Value
  11.     End If
  12.   Next
  13. Next
What I've done here is exactly the same as the first example - until lines 5-12, where I have inserted another FOR loop. Its job is to get the properties of each oItem returned by the WMI query, and return that item's name and value properties. So this form can be handy when you do not already know the name of each property that will be returned by the WMI call.

Also take note of the IF clause at lines 7-8. Some WMI properties will be returned as arrays, which take a bit more planning and coding to display properly. For this example I simplified things by simply ignoring the contents of the array, and printing notification that this was done.

These two examples of WMI query can form the basis of many, if not most, of your WMI information retreival scripts. Often you'll only need to change the WMI classname near the end of line 3 (in both examples).


0 Comments  Show recent to old
Post a comment


 RSS of this page