Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 882
S R Avatar asked Oct 31 '14 17:10

S R


1 Answers

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";
                 }
    }
like image 153
briantist Avatar answered Nov 27 '22 13:11

briantist