2014-12-11 81 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} 

這將使用常規(「成功」)流在內部保持的所有的東西的軌道,那麼這一切猛推到實際的控制檯,而不是把它扔了,因爲我想到事件通常做的。

相關問題