【问题标题】:Handling null WMI query in vbscript [duplicate]在 vbscript 中处理空 WMI 查询 [重复]
【发布时间】:2020-10-07 08:52:05
【问题描述】:

我正在尝试处理colItems 将为空的情况,因为计算机没有 WMI 类 Win32_TSLicenseKeyPack。然而我所有的尝试都没有成功。

这是我没有空检查的工作代码:

Set oWsh = WScript.CreateObject("WScript.Shell")   
Set oWshSysEnv = oWsh.Environment("PROCESS")   
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")   
Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("select AvailableLicenses,IssuedLicenses,ProductVersion,TypeAndModel from Win32_TSLicenseKeyPack")
For Each objItem In colItems     
strTS = objItem.ProductVersion & " | " & objItem.TypeAndModel & " | " & objItem.AvailableLicenses & " | " & objItem.IssuedLicenses
wscript.echo strTS
Next

我一直在尝试使用 IsEmptyIsObjectIf<> "" 等功能,但还是没有成功。

按照评论中的建议,我尝试了If not colItems is nothing then

但如果我这样做,我会收到以下代码的以下错误:

 Set oWsh = WScript.CreateObject("WScript.Shell")   
    Set oWshSysEnv = oWsh.Environment("PROCESS")   
    Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")   
    Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("select AvailableLicenses,IssuedLicenses,ProductVersion,TypeAndModel from Win32_TSLicenseKeyPack")
    
    If not colItems is nothing then
        For Each objItem In colItems     
        strTS = objItem.ProductVersion & " | " & objItem.TypeAndModel & " | " & objItem.AvailableLicenses & " | " & objItem.IssuedLicenses
        wscript.echo strTS
        Next
    Else
    wscript.echo "is empty"
    End If

【问题讨论】:

  • 你试过If not colItems is nothing then吗?
  • 请不要张贴错误信息的图片。另见meta.stackoverflow.com/questions/303812/…
  • @tripleee 图像也不是很好,它裁剪了实际的错误描述。
  • 您确定colItems 正在返回null?如果它在Is Nothing 之后仍然运行For 循环,请检查您仍然有一个对象引用,所以可以尝试.Count > 0,正如重复项所暗示的那样......
  • 您还获得了两次 WMI 服务对象,但是以不同的方式,这是怎么回事? (GetObject("winmgmts:\\.\root\CIMV2") vs GetObject("WinMgmts:root/cimv2") 而你似乎甚至没有使用第一个。

标签: vbscript wmi


【解决方案1】:

这是 lankymarte 建议的带有 .count 函数的工作代码

Set oWsh = WScript.CreateObject("WScript.Shell")   
Set oWshSysEnv = oWsh.Environment("PROCESS")  
Set colItems = GetObject("WinMgmts:root/cimv2").ExecQuery("select AvailableLicenses,IssuedLicenses,ProductVersion,TypeAndModel from Win32_TSLicenseKeyPack")

dim i: i = getCount(colItems)

if (i < 0) then
    wscript.echo "empty"
else
    For Each objItem In colItems     
    strTS = objItem.ProductVersion & " | " & objItem.TypeAndModel & " | " & objItem.AvailableLicenses & " | " & objItem.IssuedLicenses
    wscript.echo strTS
    Next
end if

function getCount(wmiCol)
    on error resume next
    getCount = colItems.Count
    if (err.number <> 0) then getCount = (-1)
    on error goto 0
end function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多