(Powershell)抓住“Get-WinEvent:没有发现任何事件”Get-WinEvent

时间:2014-10-31 17:12:00

标签: powershell powershell-v2.0 powershell-v3.0 powershell-ise

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

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

我跑的命令 -

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

我在下面尝试但无法使其正常工作 -

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

请帮忙。感谢

1 个答案:

答案 0 :(得分:3)

这是一个非终止错误,不会被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";
                 }
    }