powershell - 捕获 Get-EventLog 错误

标签 powershell

我正在编写一个简单的脚本来解析一些事件日志,但我需要在没有结果或 instanceid 无效时消除一些错误:

PS C:\> get-eventlog Application -instanceid 1111

Get-EventLog : No matches found
At line:1 char:13
  + get-eventlog <<<<  Application -instanceid 1111
      + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
      + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand

我可以这样做并将其静音,但这也会静音其他错误:

PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch { }

我试过了,但没用:

PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] { }

Unable to find type [ObjectNotFound]: make sure that the assembly containing this type is loaded.
At line:1 char:91
  + try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] <<<< { }
     + CategoryInfo          : InvalidOperation: (ObjectNotFound:String) [], RuntimeException
     + FullyQualifiedErrorId : TypeNotFound

最佳答案

您可以使用 -ErrorAction SilentlyContinue 并在它之后检查您的 $error 变量,

$error[0] 

它将始终包含最后一个错误对象。

关于powershell - 捕获 Get-EventLog 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26434831/

相关文章:

powershell - 如何使用 Powershell 显示用户的 OU

xml - 使用 PowershellWhere-Object 过滤 xml

windows - 如何在 PowerShell 中获取错误的行号

powershell - 将变量串在一起以清除它们是否可以?

powershell - 写入事件日志以查找错误

file - Powershell 计数文件扩展名以及每个扩展名的总文件大小

powershell - 连接-AzureRmAccount : accessing_ws_metadata_exchange_failed

Powershell Web 请求不会在 4xx/5xx 上引发异常

powershell - 为 cmdlet 定义创建额外的默认参数

powershell - WMI筛选器出现问题