Hey everyone! I'm working with PowerShell to pull the last two application logs with event ID 654 and calculate the time difference between them. My goal is to log a message if the time difference exceeds 30 minutes. I've put together a script that works, but I'm looking for tips from those who are more experienced. How can I improve my script's performance and reliability? Here's what I have so far:
```powershell
$search = "CMP.DOMAIN"
$Events = Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 |
Where-Object Message -like "*$search*" |
Select-Object -First 2
$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."
}
```
I've encountered some issues that I believe could be improved. Thanks for any advice!
3 Answers
You might want to add a check for the number of events returned. Right now, if your query returns fewer than 2 events, your script will fail because it tries to access nonexistent indices. Also, using `Get-WinEvent -FilterXPath` could make your queries faster if you find performance to be an issue.
If you optimize your script with XPath to get events within the last 30 minutes, you could simply count the number of events returned. If you get at least 2, that's a success; otherwise, it's a fail. Just remember, you can also check for a single event in that time frame to verify if the process is working correctly.
Your script looks good for the most part, but there's a logic issue. The heartbeat event may not be reliable since it gets triggered only when there are no passwords to sync, which could lead to false positives about delays. Instead, consider using the Entra Connect Health monitoring service for more accurate tracking.
Thanks for the tip! What's a good run frequency to set for the task scheduler since I need to catch the log every 30 minutes?