PingHost.vbs

'=========================================================================
' PingHost.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: [email protected]
' WEB: https://sigkillit.com
' DATE: 1/17/2013
' COMMENTS: Pass a hostname or IP to the function and the number of times
' you wish to ping the host/IP, and it will return whether it is succesful
' or not.
' EXAMPLE: Ping by Hostname
' Dim strHost: strHost = "Server"
' Dim intCount: intCount = 4
' EXAMPLE: Ping by IP
' Dim strHost: strHost = "192.168.1.1"
' Dim intCount: intCount = 4
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim strHost: strHost = "Server"
Dim intCount: intCount = 4
' ------ END CONFIGURATION ------

Wscript.Echo PingHost(strHost, intCount)

Private Function PingHost(strHostOrIP, count)

	On Error Resume Next ' Start Error Handling

	'Set Variables
	Dim objPing, objRetStatus, i, strResult: strResult = ""

	For i = 1 to count
		Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & strHostOrIP & "'")
		For Each objRetStatus in objPing
			If IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 Then
				strResult = "!~ERROR~!" & objRetStatus.StatusCode
				'WScript.Echo "Status code is " & objRetStatus.StatusCode
			Else
				strResult = "OK"
				'Wscript.Echo "Bytes = " & vbTab & objRetStatus.BufferSize
				'Wscript.Echo "Time (ms) = " & vbTab & objRetStatus.ResponseTime
				'Wscript.Echo "TTL (s) = " & vbTab & objRetStatus.ResponseTimeToLive
			End If
		Next

		' Error Check
		If Err.Number <> 0 Then
		strResult = "!~ERROR~!"
		End If

		'Check For Success
		If strResult = "OK" Then
			Exit For
		End If
		count = count -1
	Next

	'Return Result
	PingHost = strResult

	On Error GoTo 0 ' End Error Handling

End Function