Submitted By: Paul Smith

Repeatedly pings a target device to test network connectivity. On ping failure, the script can either case the computer to beep (useful for running in the background), or can write a time-stamped failure message to an output file (useful for running over a period of time).

Visual Basic
Edit|Remove
'Pings a remote host and beeps when ping is unsuccessful
Option Explicit

Dim strTarget
Dim intCount
Dim blnWriteToFile
Dim fileSys
Dim fileOut
Dim blnQuiet
Dim strArg
Dim objShell
Dim objExec
Dim objStdOut
Dim strLine
Dim strOutFile

Const FOR_APPENDING = 8
Const CREATE = True

'Process Arguments
strTarget = UCase(WScript.Arguments.Named.Item("t"))
If strTarget = "" Then
	DisplayUsage
	WScript.Quit
End If

intCount = CLng(WScript.Arguments.Named.Item("c"))

blnWriteToFile = True
strOutFile = LCase(WScript.Arguments.Named.Item("o"))
If strOutFile = "" Then
	blnWriteToFile = False
End If
If blnWriteToFile = True Then
	Set fileSys = CreateObject("Scripting.FileSystemObject")
	Set fileOut = fileSys.OpenTextFile(strOutFile, FOR_APPENDING, CREATE)
End If

blnQuiet = False
For Each strArg in WScript.Arguments
	If strArg = "/q" Then
		blnQuiet = True
	End If
Next

'Run ping in shell, capture output
Set objShell = CreateObject("WScript.Shell")
If intCount = 0 Then
	Set objExec = objShell.Exec ("ping -t " & strTarget)
Else
	Set objExec = objShell.Exec ("ping -n " & intCount & " " & strTarget)
End If
Set objStdOut = objExec.StdOut

'Interpret output
While Not objStdOut.AtEndOfStream
	strLine = objStdOut.ReadLine
	WScript.Echo strLine
	If InStr(strLine, "Request timed out.") or InStr(strLine, "Destination host unreachable.") Then
   		If blnQuiet = False Then
    		objShell.Run "%comspec% /c echo " & Chr(07), 0, True
    	End If
    	If blnWriteToFile = True Then
    		fileOut.WriteLine(strTarget & " - Ping failed:  " & Date & ", " & Time)
    	End If
   	End If
Wend

'Cleanup
If blnWriteToFile = True Then
	fileOut.Close
End If


Sub DisplayUsage
	WScript.Echo vbCrLf & "Repeatedly pings a target device and beeps when device does not respond"
	WScript.Echo vbCrLf & "Usage:  alive /t:<target> [/c:<count>] [/o:<outputFile>] [/q]" & vbCrLf
	WScript.Echo "        /t              - target can be device name or IP address"
	WScript.Echo "        /c              - Number of times to ping target.  If omitted, ping will run"
	WScript.Echo "                          indefinitely (same as ""ping -t"").  Must hit Ctrl-C to cancel."
	WScript.Echo "        /o:<outputFile> - sends failure timestamp info to specified output file"
	WScript.Echo "                          i.e.:  ""10.1.1.1 - Ping failed:  12/1/2003, 12:34:16 PM"""
	WScript.Echo "        /q              - Quiet mode.  No beep will be generated when ping fails."
	WScript.Quit
End Sub