2014-12-11 89 views
2

通常情况下,PowerShell错误以红色文本显示在控制台中。由事件称为脚本块内然而如何查看在PowerShell事件处理程序中生成的错误消息?

red-text error message screenshot

错误,不显示在控制台上同样的错误:你可以使用Write-Error 'This is an example non-terminating error message.'进行测试。该脚本演示了这种现象:

$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

如果您将该块的全部内容封装到Write-Host的重定向中,它就可以工作。

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

这将使用常规(“成功”)流在内部保持的所有的东西的轨道,那么这一切猛推到实际的控制台,而不是把它扔了,因为我想到事件通常做的。

相关问题