(Powershell) Catch "Get-WinEvent : No events were found" Get-WinEvent

S R picture S R · Oct 31, 2014 · Viewed 8.6k times · Source

When I run a below command to list log by ID, it says Get-WinEvent : No events were found that match the specified selection criteria.

How can I catch this exception and display a simple message saying "No events found".

Command which I ran-

Get-WinEvent -FilterHashtable @{LogName="Application";ID="191"}

I tried below below but could not make it working-

try { Get-WinEvent -FilterHashtable @{LogName="Application";ID="191"}
    }

catch [Exception] {
        if ($_.Exception -match "No events were found that match the specified selection criteria") {
        Write-Host "No events found";
                 }
    }

Please help. Thanks

Answer

briantist picture briantist · Oct 31, 2014

It's a non-terminating error which won't get caught by try/catch. Use -ErrorAction Stop.

try { Get-WinEvent -FilterHashtable @{LogName="Application";ID="191"} -ErrorAction Stop
    }

catch [Exception] {
        if ($_.Exception -match "No events were found that match the specified selection criteria") {
        Write-Host "No events found";
                 }
    }