tags:

views:

159

answers:

1

I have the following VBScript:

SET Wmi = GetObject("winmgmts:\\.\root\cimv2")
SET QR = Wmi.ExecQuery("SELECT * FROM Win32_Processor")
MsgBox("" & QR.Count)

Which works perfectly fine. However, when I query something which doesn't exist:

SET Wmi = GetObject("winmgmts:\\.\root\cimv2")
SET QR = Wmi.ExecQuery("SELECT * FROM Win32_DoesNotExist")
MsgBox("" & QR.Count)

I get the following error message:

Script: E:\test.vbs
Line: 3
Char: 1
Error: Invalid class
Code: 80041010
Source: SWbemObjectSet

How can I know whether the QR object is valid?

If I call TypeName(QR), it will say SWbemObjectSet, but as soon as I try to query one of its properties, it fails with the above message.

I've googled for this error, and most pages seem to say something to the effect of "just don't do that query". This is not an option, unfortunately, because I want to run the same script on multiple versions of Windows, and Microsoft occasionally deprecates WMI classes in new versions of Windows. I want my script to handle that gracefully.

+2  A: 

Edit;

.Count seems to work for a schema query;

dim testNs: testNs = "Win32_DoesNotExist"
dim colClasses: set colClasses = Wmi.ExecQuery("Select * From Meta_Class where __Class = """ & testNs  & """")
msgbox colClasses.count

You could wrap-n-trap the access error;

SET QR = Wmi.ExecQuery("SELECT * FROM Win32_DoesNotExist")

dim i: i = getCount(QR)

if (i < 0) then
    msgbox "oopsy"
else
    msgbox "count is " & i
end if

function getCount(wmiCol)
    on error resume next
    getCount = QR.Count
    if (err.number <> 0) then getCount = (-1)
    on error goto 0
end function
Alex K.
Yup, a bit ulgy but it does the trick. Thanks!
jqno