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
            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
    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.")
	MsgBox("ERROR: Can not reach host localhost.")
End If
Filed under: VBS

VBS Includes

I used the code to in a script to source out some code from a realy big script. I lost it and didn’t find again. Now I was searching for a way to do includes like in PHP and other languages. I didn’t found an include function or equal. But I got sth. which does nearly the same:

Dim sScriptPath
' Path to this script
sScriptPath = Left(sScriptPath, Len(WScript.ScriptFullName) - Len(WScript.ScriptName))
' load the file in the path and execute the code
Execute CreateObject("Scripting.FileSystemObject").OpenTextFile(sScriptPath & "file2include.inc").ReadAll

I recommend to rename the files from .vbs to .inc or sth. else to prevent manual execution of the files.

Filed under: VBS