代码之家  ›  专栏  ›  技术社区  ›  jqno

VBScript:如何检查SWbemObjectSet的有效性?

  •  4
  • jqno  · 技术社区  · 15 年前

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

    效果很好。但是,当我查询不存在的东西时:

    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 对象有效吗?

    TypeName(QR) SWbemObjectSet

    我在google上搜索过这个错误,大多数页面似乎都说了一些类似“不要做那个查询”的话。不幸的是,这不是一个选项,因为我想在多个版本的Windows上运行同一个脚本,而Microsoft偶尔会在新版本的Windows中否决WMI类。我希望我的剧本能处理得很好。

    1 回复  |  直到 15 年前
        1
  •  5
  •   Alex K.    15 年前

    编辑;

    .Count

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

    您可以包装n陷阱访问错误;

    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