Tuesday, June 26, 2007

WMI Ping (Win32_PingStatus)

The code below is an example in how to use Win32_PingStatus class in WMI to check a remote machine's status on the network.

Code Snippet:

  1. Function PingHost(sTarget)
  2. Set cPingResults = GetObject("winmgmts:{impersonationLevel=impersonate}//" & _
  3. sHost & "/root/cimv2"). ExecQuery("SELECT * FROM Win32_PingStatus " & _
  4. "WHERE Address = '" + sTarget + "'")
  5. For Each oPingResult In cPingResults
  6. If oPingResult.StatusCode = 0 Then
  7. If LCase(sTarget) = oPingResult.ProtocolAddress Then
  8. WScript.Echo sTarget & " is responding"
  9. Else
  10. WScript.Echo sTarget & "(" & oPingResult.ProtocolAddress & ") is responding"
  11. End If
  12. Wscript.Echo "Bytes = " & vbTab & oPingResult.BufferSize & _
  13. vbTab & "Time (ms) = " & vbTab & oPingResult.ResponseTime & _
  14. vbTab & "TTL (s) = " & vbTab & oPingResult.ResponseTimeToLive & _
  15. vbTab & "Hostname = " & vbTab & oPingResult.ProtocolAddressResolved
  16. Else
  17. WScript.Echo sTarget & " is not responding"
  18. WScript.Echo "Status code is " & oPingResult.StatusCode
  19. WScript.Echo "*********************************"
  20. End If
  21. Next
  22. End Function

If at first you fail, call it version 1.0

1 comment:

Stephen Bach said...

The "&" in Line 10 should be changed to "&".