VBScript: how to inspect validity of SWbemObjectSet?

倾然丶 夕夏残阳落幕 提交于 2019-12-23 15:28:25

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2920059/vbscript-how-to-inspect-validity-of-swbemobjectset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!