开发者

VBScript: how to inspect validity of SWbemObjectSet?

开发者 https://www.devze.com 2023-01-01 00:58 出处:网络
I have the following VBScript: SET Wmi = GetObject(\"winmgmts:\\\\.\\root\\cimv2\") SET QR = Wmi.ExecQuery(\"SELECT * FR开发者_如何学COM Win32_Processor\")

I have the following VBScript:

SET Wmi = GetObject("winmgmts:\\.\root\cimv2")
SET QR = Wmi.ExecQuery("SELECT * FR开发者_如何学COM 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消