问题描述
我有以下 VBScript:
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)
我收到以下错误消息:
Script: E:\test.vbs
Line: 3
Char: 1
Error: Invalid class
Code: 80041010
Source: SWbemObjectSet
我如何知道 QR
对象是否有效?
How can I know whether the QR
object is valid?
如果我调用 TypeName(QR)
,它会说 SWbemObjectSet
,但是一旦我尝试查询其属性之一,它就会失败并显示上述消息.
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.
我在谷歌上搜索过这个错误,大多数页面似乎都说不要做那个查询".不幸的是,这不是一个选项,因为我想在多个版本的 Windows 上运行相同的脚本,而 Microsoft 偶尔会在新版本的 Windows 中弃用 WMI 类.我希望我的脚本能够优雅地处理这个问题.
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
似乎适用于模式查询;
.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
您可以对访问错误进行 wrap-n-trap;
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
这篇关于VBScript:如何检查 SWbemObjectSet 的有效性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!