So I've seen a few requests lately concerning the ability to ping to check for connectivity within a vbscript. Most implementations I've seen call ping.exe using the exec method of wscript.shell and read the output via stdout. While this works just fine, I think using WMI to ping is cleaner and easier to work with. There is no need to read the output and try to extract what you want from a string like you do when using ping.exe. I hope some find this useful.
The Reachable function will return True or False depending on whether the address provided is reachable or not. The address can be provided with an IP address or Computer Name The ResolveIP function will return an IPAddress that corresponds to the Computer Name you provide
I put together a simple "Connectivity Monitor" using Win32_PingStatus. You can download it from here (I put it in a zip because of the images used for it): ConnectivityMonitor
'========================================================================== ' The following function will test if a machine is reachable via a ping ' using WMI and the Win32_PingStatus '========================================================================== If Reachable("10.50.138.48") Then WScript.Echo "Computer is Reachable" Else WScript.Echo "Computer is Unreachable!" End If
Function Reachable(strComputer) ' On Error Resume Next
Dim wmiQuery, objWMIService, objPing, objStatus
wmiQuery = "Select * From Win32_PingStatus Where " & _ "Address = '" & strComputer & "'"
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set objPing = objWMIService.ExecQuery(wmiQuery)
For Each objStatus in objPing If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then Reachable = False 'if computer is unreacable, return false Else Reachable = True 'if computer is reachable, return true End If Next End Function
ResolveIP Function
CODE
'========================================================================== ' The following function will resolve a computer name to its ip address ' using WMI and the Win32_PingStatus '========================================================================== WScript.Echo ResolveIP("Computer1")
Function ResolveIP(strComputer) ' On Error Resume Next
Dim wmiQuery, objWMIService, objPing, objStatus
wmiQuery = "Select * From Win32_PingStatus Where " & _ "Address = '" & strComputer & "'"
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set objPing = objWMIService.ExecQuery(wmiQuery)
For Each objStatus in objPing If IsNull(objStatus.StatusCode) Or objStatus.Statuscode<>0 Then ResolveIP = "Computer is Unreachable!" Else ResolveIP = objStatus.ProtocolAddress End If Next End Function