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

2

7

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

Groenendael answered 31/10, 2014 at 17:12 Comment(0)
A
9

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";
                 }
    }
Alcot answered 31/10, 2014 at 17:20 Comment(0)
N
0

Alternatively, you can check the value of FullyQualifiedErrorId.

try {
    # Call Get-Winevent
}
catch [Exception] {
    if ($_.FullyQualifiedErrorId -match "NoMatchingEventsFound") {
        # Do something
    }
}

This method seems more portable as the value of Exception can vary depending on the language settings.

Neoprene answered 18/10 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.