Slager Peters
asked on
Powershell Comparison
Hi,
I'm trying to write a script that compares time between servers.
So, i'm getting time from one server and time from the second one.
With the help of new-timespan, i'm getting the difference in time, written in seconds.
After that I want to have a result:
If the difference is less or equal tha 15 seconds: No problem.
If the difference is bigger: Problem
The thing is: my script thinks the servers are always in sync, even if they are not.
So, I think my comparison is not working.
What am I doing wrong ?
I thought that, maybe it's because i'm comparing a variable to a number.
So I tried to convert the content of the variable to a string. Didn't help.
Placeing "" around the number of secaonds didn;t make a differnece as well.
The script:
I'm trying to write a script that compares time between servers.
So, i'm getting time from one server and time from the second one.
With the help of new-timespan, i'm getting the difference in time, written in seconds.
After that I want to have a result:
If the difference is less or equal tha 15 seconds: No problem.
If the difference is bigger: Problem
The thing is: my script thinks the servers are always in sync, even if they are not.
So, I think my comparison is not working.
What am I doing wrong ?
I thought that, maybe it's because i'm comparing a variable to a number.
So I tried to convert the content of the variable to a string. Didn't help.
Placeing "" around the number of secaonds didn;t make a differnece as well.
The script:
# PRTG Exit codes
# 0 OK
# 1 WARNING
# 2 System Error (e.g. a network/socket error)
# 3 Protocol Error (e.g. web server returns a 404)
# 4 Content Error (e.g. a web page does not contain a required word)
$server2 = "APP02"
$server3 = "APP03"
$time2 = Invoke-Command –ComputerName $server2 -ScriptBlock {Get-Date -format T}
$time3 = Invoke-Command –ComputerName $server3 -ScriptBlock {Get-Date -format T}
write-host $time2
write-host $time3
$diff = NEW-TIMESPAN –Start $time2 –End $time3
$sec = $diff.totalseconds
$sec -Replace "-","" | Out-String
if ($sec -le 15)
{
$result = "0:OK - There is no difference in time"
$result
}
elseif ($sec -gt 15)
{
$result = "2:Error - Time is no longer in sync"
$result
}
#Format exitcode
$exitcode = $result -replace ":.*"
#Print string for PRTG
#Exit script
#write-host $exitcode
exit $exitcode
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
oBdA's script is exactly what I needed.
ASKER
Thanks for your comment: you are a hero !
I just found something that worked, by changing these lines
Open in new window
but your solution is much more better !
Thanks !