VBScript运行时错误:所需对象(Windows 2003)

时间:2016-09-21 17:45:45

标签: vbscript

尝试从函数中返回字符串会导致需要对象错误。 在Windows 2003上运行此代码。注意:在w2k3上,Win32_OperatingSystem执行此操作 不支持=@单身人士,这就是我们使用For Each ... / Exit Function

的原因
Function GetLocalTime()
    Dim wmi, itm
    Set wmi = GetObject("winmgmts:root\cimv2")
    For Each itm in wmi.ExecQuery("SELECT * FROM Win32_OperatingSystem")
        ' NEXT LINE THROWS 'Object required' error
        GetLocalTime = itm.LocalDateTime
        Exit Function
    Next
End Function

Dim started : Set started = GetLocalTime
WScript.Echo "started " & started

1 个答案:

答案 0 :(得分:2)

想出来。报告的错误消息发生在GetLocalTime()函数的正文中,但错误实际上来自调用。需要删除Set。这是更正后的代码:

Function GetLocalTime()
    Dim wmi, itm
    Set wmi = GetObject("winmgmts:root\cimv2")
    For Each itm in wmi.ExecQuery("SELECT * FROM Win32_OperatingSystem")
        GetLocalTime = itm.LocalDateTime
        Exit Function
    Next
End Function

Dim started : started = GetLocalTime  ' <-- CHANGED LINE
WScript.Echo "started " & started