连接WMI时需要获取错误对象

时间:2016-04-14 02:26:36

标签: vbscript wmi

我想创建一个Excel日志文件来记录主机名,IP,ping的状态以及WMI连接的状态。当我尝试运行脚本时,我遇到了错误"需要对象",但是当我检查代码时,我无法找到应该更改代码的位置。

On Error Resume Next
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InputFile = Fso.OpenTextFile("file.txt", 1)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intRow = 2

objExcel.Cells(1, 1).Value = "Hostname"
objExcel.Cells(1, 2).Value = "IP"
objExcel.Cells(1, 3).Value = "Ping"
objExcel.Cells(1, 4).Value = "WMI"

Do While Not (InputFile.atEndOfStream)
  hostname = InputFile.ReadLine

  Set WshShell = CreateObject("WScript.Shell")
  Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)

  objExcel.Cells(intRow, 1).Value = hostname

  Select Case Ping
    Case 0 objExcel.Cells(intRow, 3).Value = "On Line"
    Case 1 objExcel.Cells(intRow, 3).Value = "Off Line"
    Case 2 objExcel.Cells(intRow, 3).Value = "N/A"
  End Select

  Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & hostname & "\root\cimv2")
  Set IPconfig = objWMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

  If Err.Number = 0 Then
    objExcel.Cells(intRow, 4).Value = "Pass"
    For Each IP In IPconfig
      If Not IsNull(IP.IPAddress) Then
        For i = LBound(IP.IPAddress) To UBound(IP.IPAddress)
          objExcel.Cells(intRow, 2).Value = IP.IPAddress(i)
        Next
      Else
        objExcel.Cells(intRow, 2).Value = "N/A"
      End If
    Next
  Else
    objExcel.Cells(intRow, 4).Value = Err.Description
  End If

  intRow = intRow + 1
Loop

objExcel.Range("A1:B1:C1:D1").Select
objExcel.Selection.Interior.ColorIndex = 19
objExcel.Selection.Font.ColorIndex = 11
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit

InputFile.Close
On Error Goto 0

Set objExcel = Nothing
Set Fso      = Nothing
Set InputFile = Nothing
Set objWMIService = Nothing
Set WshShell = Nothing
Set Ping = Nothing
Set IPconfig = Nothing

MsgBox "Done Analyse"
objExcel.Quit
Wscript.Quit

1 个答案:

答案 0 :(得分:2)

Set Ping = WshShell.Run("ping -n 1 " & hostname, 0, True)

WshShell返回一个不是对象的整数。 Set仅为对象的用户。所以只需删除set字词。

Wmi可以做自己的ping。这是命令行版本,但您可以将其插入到用于NetworkAdaptor的WMI语句中。

wmic /append:"textfile.txt" path win32_pingstatus where "address='127.0.0.1' and responsetime > 100" get responsetime,timestamprecord

有关与vbscript类型wmic path win32_pingstatus get /?

相同的帮助