Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

wmi - VBScript: how to inspect validity of SWbemObjectSet?

I have the following VBScript:

SET Wmi = GetObject("winmgmts:\.
ootcimv2")
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:\.
ootcimv2")
SET QR = Wmi.ExecQuery("SELECT * FROM Win32_DoesNotExist")
MsgBox("" & QR.Count)

I get the following error message:

Script: E:est.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...