I use PowerShell to retrieve the last two application logs with event ID 654 and calculate the time difference between them. If the time difference between the two logs is more than 30 minutes, I will generate a log.
I wrote something like the following. I tested it, and it works. But, what advice would you experts give me? How can I write it better?
PS C:\Windows\system32> $timediff
Days : 0
Hours : 0
Minutes : 30
Seconds : 28
Milliseconds : 0
Ticks : 18280000000
TotalDays : 0.0211574074074074
TotalHours : 0.507777777777778
TotalMinutes : 30.4666666666667
TotalSeconds : 1828
TotalMilliseconds : 1828000
PS C:\Windows\system32> $time1
Friday, August 8, 2025 8:41:53 AM
PS C:\Windows\system32> $time2
Friday, August 8, 2025 8:11:25 AM
Script:
$search = "CMP.DOMAIN"
#$Events = Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 -Newest 2
$Events = Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 -Newest 2 |
Where-Object { $_.Message.ToUpperInvariant().Contains($search.ToUpperInvariant()) }
$time1 = $Events[0].TimeGenerated
$time2 =$Events[1].TimeGenerated
$timediff = $time1 - $time2
if ($timediff.TotalMinutes -gt 30) {
Write-host "There is a delay in password synchronization." -BackgroundColor Cyan
}
else {
Write-host "There is no delay in password synchronization."
}