powershell - 如何在Powershell中捕获System.Diagnostics.Eventing.Reader错误

标签 powershell error-handling custom-error-handling

代码如下:

foreach ($machine in $lbx_workstations.SelectedItems)
      {
      $temp = (get-winevent -computername $machine -FilterXML $commandString -ErrorAction SilentlyContinue -ErrorVariable eventerr|
         Select MachineName, TimeCreated, LevelDisplayName, ID, ProviderName, Message) 
blah blah blah...

我创建了一个自定义错误变量$ eventerr,当get-winevent cmdlet找不到任何与XML命令字符串中的条件匹配的事件时,该变量就可以正常工作。但是,问题是这样的:如果XML命令字符串无效,则会在$ error变量而不是$ eventerr变量中创建错误。我想将该错误存储在我的自定义错误变量中,但是我不知道它来自哪里或是什么产生的。或者实际上为什么它尚未包含在我的自定义变量中。当我查看这两种不同类型的错误时,这是​​我得到的输出:
PS C:\Temp> $error[0].fullyqualifiederrorid
System.Diagnostics.Eventing.Reader.EventLogException,Microsoft.PowerShell.Commands.GetWinEventCommand

PS C:\Temp> $error[1].fullyqualifiederrorid
NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand 

我可以在自定义变量中捕获“NoMatchingEventsFound”错误,但不能捕获System.Diagnostics.Eventing ...错误。

有什么办法可以将“System.Diagnostics.Eventing ...”错误放入我的自定义错误变量中?

最佳答案

当PowerShell尝试将$commandString转换为XmlDocument(-FilterXml参数的类型)时,可能会发生这种情况。我认为您无法在error变量中捕获错误,因为它发生在调用Get-WinEvent之前。最好的选择是在尝试将$commandString传递给Get-WinEvent之前,先对其进行验证。

try
{
    $xmlDoc = New-Object 'Xml.XmlDocument'
    $xmlDoc.LoadXml( $commandString )
}
catch
{
    # Or do some other kind of error handling.  You're the driver!
    Write-Error ('Oh no!  Bad XML!  What are you thinking?!')
}

$lbx_workstationg.SelectedItems |
    ForEach-Object { Get-WinEvent -ComputerName $_ -FilterXml $commandString -ErrorAction SilentlyContinue -ErrorAction eventerr } |
    Select-Object MachineName, TimeCreated, LevelDisplayName, ID, ProviderName, Message

话虽这么说,我注意到有时使用-ErrorVariable并不会由于放入指定的错误变量而导致所有错误。我从来不知道为什么。我通常最终会退回到使用$Error。您可以通过适当的索引获取特定于命令的错误:
$errorCount = $Error.Count
$lbx_workstationg.SelectedItems |
    ForEach-Object { Get-WinEvent -ComputerName $_ -FilterXml $commandString -ErrorAction SilentlyContinue } |
    Select-Object MachineName, TimeCreated, LevelDisplayName, ID, ProviderName, Message
$winEventError = $Error[0..($Error.Count - $errorCount)]

关于powershell - 如何在Powershell中捕获System.Diagnostics.Eventing.Reader错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561440/

相关文章:

azure - 获取Azure时间触发函数的当前函数名称

azure - 使用 Azure Yaml 管道通过主体中的 secret 变量调用 powershell RestMethod

powershell - PowerShell 路径中的转义美元符号不起作用

error-handling - 仍未决定如何处理Swift 2中的错误

powershell - 没有参数时如何在powershell中显示Get-Help

xmllint 捕获错误代码

c - 如何在 dup2 中使用 perror?

c# - Web api dotnet 核心中 Api 版本控制错误的自定义错误响应

python - python 中的异常处理和继续 for 循环

ios - 如何使 cordova ios 应用程序崩溃