3
Jan/090
Jan/090
Quickie: How to ping a host in vbs? I got two ways…
I need to ping a host via visual basic script. Some years ago I started to use this function:
Function Ping(strHost) Dim objSh, strCommand, intWindowStyle, blnWaitOnReturn blnWaitOnReturn = True intWindowStyle = 0 strCommand = "%ComSpec% /C %SystemRoot%\system32\ping.exe -n 1 " _ & strHost & " | " & "%SystemRoot%\system32\find.exe /i " _ & Chr(34) & "TTL=" & Chr(34) Set objSh = WScript.CreateObject("WScript.Shell") Ping = Not CBool(objSh.Run(strCommand, intWindowStyle, blnWaitOnReturn)) Set objSh = Nothing End Function
Yes, quiet hackish.
Now I use wmi for checking some hosts for being alive or dead in vbs:
Function Ping(strHost) Dim oPing, oRetStatus, bReturn Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address='" & strHost & "'") For Each oRetStatus In oPing If IsNull(oRetStatus.StatusCode) Or oRetStatus.StatusCode <> 0 Then bReturn = False ' WScript.Echo "Status code is " & oRetStatus.StatusCode Else bReturn = True ' Wscript.Echo "Bytes = " & vbTab & oRetStatus.BufferSize ' Wscript.Echo "Time (ms) = " & vbTab & oRetStatus.ResponseTime ' Wscript.Echo "TTL (s) = " & vbTab & oRetStatus.ResponseTimeToLive End If Set oRetStatus = Nothing Next Set oPing = Nothing Ping = bReturn End Function
The function is completely different – the result is the same.
Here a quick example how to use these functions:
If Ping("localhost") Then MsgBox("OK: Host localhost is reachable.") Else MsgBox("ERROR: Can not reach host localhost.") End If







