(Powershell) 捕获“Get-WinEvent : 未找到事件” Get-WinEvent

S R*_*S R 5 powershell powershell-ise powershell-2.0 powershell-3.0

当我运行以下命令按 ID 列出日志时,它说 Get-WinEvent : No events were found that match the specified selection criteria.

如何捕获此异常并显示一条简单的消息“未找到事件”。

我运行的命令-

Get-WinEvent -FilterHashtable @{LogName="Application";ID="191"}
Run Code Online (Sandbox Code Playgroud)

我在下面尝试过,但无法使其工作-

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";
                 }
    }
Run Code Online (Sandbox Code Playgroud)

请帮忙。谢谢

bri*_*ist 7

这是一个非终止错误,不会被try/捕获catch。使用-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";
                 }
    }
Run Code Online (Sandbox Code Playgroud)