Date created: Tuesday, March 22, 2011 11:08:41 PM. Last modified: Thursday, December 13, 2012 11:41:20 AM

VPN Ping Test

This is a powershell script I wrote to test if connectivity to a DC is still active. It is scheduled to run every 5 minutes on a DC in site1 to ping a DC in site2 and email me if there was a problem with the ping.

The script uses the 'test-connection' cmdlet with the -quiet option. The -quiet option suppresses all output and returns a simply boolean value of weather any of the ICMP echo requests returned successfully. It will be false if all four request fails otherwise true. The 'test-connection' cmdlet can return a WMI Win32_PingStatus object with more details but this keeps it simple (TechNet Article).

In the scenario this script runs, there is the occasional packet loss on the VPN between AD sites so I only want to know if all four echo requests fail, for that reason, the script has a $maxTries value, and only after failing three times (unless changed) will an email be sent to notify somebody of the ping failure. The stability of running a site to site VPN over ADSL is a matter for another day :)

$testServer = '172.17.0.4'
$smtpServer = "172.16.0.3"
$mailFrom = "notification@mydomain.tld"
$mailTo = "ohdearitsbroken@mydomain.tld"
$maxTries = 3
$retryDelay = 60

function SendMail () {
	$smtp = new-object Net.Mail.SmtpClient($smtpServer)
	$smtp.Send($mailFrom, $mailTo, $mailSubject, $mailBody)
}

function TestVPN ([int]$count) {
	$results = test-connection $testServer -quiet
	if($results) {
		Write-Host "vpn ping successful"
	}else{
		Write-Host "Failed attempt: $count"
		if($count -ge $maxTries) {
			Write-Host "vpn has some packet loss"
			$mailSubject = "VPN has some packet loss!"
			$mailBody = "VPN has some packet loss!"
			SendMail
		}else{
			start-sleep -s $retryDelay
			$count++
			TestVPN($count)
		}
	}
}

TestVPN(1)

This is scheduled to run every 5 minutes but whilst logged on the server a powershell box will pop up in the backgroung briefly every 5 minutes so to hide it I call it from a VBScript as a wrapper running it as a hidden window:

Set oShell = CreateObject("Wscript.Shell")
oShell.Run  "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -command & 'C:\Scripts\VPNTest.ps1'", 0

Previous page: Postgress Admin Notes
Next page: Problems