当我运行以下命令按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";
}
}
请帮忙。感谢
答案 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";
}
}