PowerShell Script to Monitor Server Date and Time using PRTG Network Monitor

10 Aug

I had an issue this morning when a hosted server was randomly 1 day out. All the date and time settings were correct, but as a lot of the web sites running on this box depend heaivily on system time, this was something that needed to be checked and monitored.

As mentioned in many previous posts, I use PRTG Network Monitor to check everything for me, and if something is wrong, it alerts me straight away. I didn’t see a built in option for this so I set about writing my own PowerShell script.

The script is pretty simple, it checks an internet time server and then checks the local time. It then compares these two times and reports back the difference in seconds.

#Dave Harris
#dave.harris.net
#10/08/2011

#PowerShell script to compare internet time to local time an return a result for PRTG Network Monitor

#Function to get date and time from internet
function Get-InternetTime {
$TcpClient = New-Object System.Net.Sockets.TcpClient
[byte[]]$buffer = ,0 * 64
$TcpClient.Connect(‘time.nist.gov’, 13)
$TcpStream = $TcpClient.GetStream()
$length = $TcpStream.Read($buffer, 0, $buffer.Length);
[void]$TcpClient.Close()
$raw = [Text.Encoding]::ASCII.GetString($buffer)
[DateTime]::ParseExact($raw.SubString(7,17), ‘yy-MM-dd HH:mm:ss’, $null).toLocalTime()
}

#Set time variables
$remotetime = (Get-InternetTime)
$localtime = (Get-date)

$timedifference = 0

#make sure we allways have a positive number (no negatives)
#10000000 ticks = 1 second
#-le = less than
if($remotetime -le $localtime)
{
$timedifference = ((($localtime – $remotetime).ticks)/10000000)
}else{
$timedifference = ((($remotetime – $localtime).ticks)/10000000)
}

#format return string for PRTG
write-host ([math]::truncate($timedifference),”:OK” )

Save this .ps1 file on the Remote system in the directory

C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXE

Then you can add it as a sensor within PRTG. Under  channels, select ‘Value’ and then set the Upper and Lower Error Limit, and also change ‘Unit’ to ‘Second(s)’ so it makes a bit more sense.

Also, I used ticks to compare the 2 times, for more information on ticks, see here.

It’s also worth noting that you will have to check that the remote server is allowed to run PowerShell scripts, otherwise you may get an error similar to:

“.ps1 cannot be loaded because the execution of scripts is disabled on this system”

To change this, go to your PowerShell and type:

Get-ExecutionPolicy

And if you need to set it, type:

Set-Execution Policy RemoteSigned

Also, there are both 32 and 64 bit versions of PowerShell, the later will most probably be used by PTRG and can be found here:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0

Now you will be alerted everytime the server time drops out of sync.