如何查看PowerShell事件处理程序中生成的错误消息?

时间:2014-12-11 02:39:19

标签: powershell events error-handling console

通常,PowerShell错误以红色文本显示在控制台中。您可以使用Write-Error 'This is an example non-terminating error message.'

对此进行测试

red-text error message screenshot

但事件调用的scriptblock内部的错误在控制台上不会显示相同的错误。这个脚本演示了这种现象:

$id='MyTimerEvent'
$timer = New-Object System.Timers.Timer
$n=0

$callback= { 
    $Script:n++
    Write-Host "TIMER: Count $n"
    if($n -eq 2){
        Write-Host "The next line should be a non-terminating error message."
        Write-Error "This is the error message."
    }
    if($n -gt 3){
        Unregister-Event -SourceIdentifier $id
    }
}

Register-ObjectEvent -InputObject $timer -SourceIdentifier $id `
                     -EventName Elapsed -Action $callback

$timer.Interval=500
$timer.AutoReset=$true
$timer.Enabled=$true

脚本的输出如下:

TIMER: Count 1 
TIMER: Count 2 
This line should be followed by a a non-terminating error message. 
TIMER: Count 3 
TIMER: Count 4

请注意,行Write-Error "This is the error message."的输出未显示在控制台中。 PowerShell seems to support the concept of redirecting output但似乎更倾向于重定向到文本文件。

如何将PowerShell事件处理程序中产生的错误定向到PowerShell控制台?

2 个答案:

答案 0 :(得分:2)

如果将块的全部内容重定向到Write-Host,则可以正常工作。

$callback = {(&{
  // ...
}) 2>&1 | Write-Host}

这在内部使用常规(“成功”)流来跟踪所有内容,然后将其全部推送到实际的控制台,而不是像我期望的那样将它扔掉。

答案 1 :(得分:0)

这是一个完整的解决方案,既输出终止的非终止错误,也输出仅错误的

$callback = {
    # wrap and invoke script block
    (& {
        # insert an empty trap to make the script block
        # output terminating errors too
        trap { }      
        Write-Error "non-terminating error"
        throw "terminating error"
    # redirect error-stream (2) to success-stream (1)
    }) 2>&1 |
    # filter errors only
    where {$_ -is [System.Management.Automation.ErrorRecord]} |
    # write to console directly (because output-stream is ignored)
    Write-Host -ForegroundColor 'Red'
}