CodexBloom - Programming Q&A Platform

PowerShell 7.3 - How to Create a Custom Function to Monitor Multiple Event Log Sources?

πŸ‘€ Views: 69 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
PowerShell EventLogs Monitoring

I'm not sure how to approach I tried several approaches but none seem to work. I'm trying to create a PowerShell script that monitors multiple Windows Event Log sources for specific events. I want to trigger a custom action whenever a certain event ID occurs across these logs. I've attempted to use Get-WinEvent, but I'm struggling with how to structure my function to efficiently filter the events and handle multiple sources concurrently. Here's a simplified version of what I've tried so far: ```powershell function Monitor-EventLogs { param ( [string[]]$LogNames, [int]$EventID, [int]$PollingInterval = 60 ) while ($true) { foreach ($LogName in $LogNames) { try { $events = Get-WinEvent -LogName $LogName -FilterXPath "*[System[EventID=$EventID]]" -ErrorAction Stop if ($events) { # Custom Action Write-Host "Event ID $EventID found in $LogName at $(Get-Date)" } } catch { Write-behavior "Failed to retrieve events from $LogName: $_" } } Start-Sleep -Seconds $PollingInterval } } ``` When I run this function with `Monitor-EventLogs -LogNames @('Application', 'System') -EventID 1000`, it works for the first log but fails silently on the second with no output. I suspect the scenario might be related to how I’m handling errors or the way I’m iterating through the log names. I also noticed that it doesn’t seem to capture events consistently if they occur rapidly in succession. Can anyone provide insights on how to ensure that I get results from all specified logs and improve the event retrieval performance? Also, is there a better way to manage concurrent log monitoring without blocking the execution? I'm working on a API that needs to handle this. Any ideas what could be causing this? For reference, this is a production desktop app.