powershellpowershell-2.0powershell-3.0powershell-ise

(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


Solution

  • 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";
                     }
        }