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控制台?