2
通常情況下,PowerShell錯誤以紅色文本顯示在控制檯中。由事件稱爲腳本塊內然而如何查看在PowerShell事件處理程序中生成的錯誤消息?
錯誤,不顯示在控制檯上同樣的錯誤:你可以使用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控制檯?