如何查看在PowerShell事件处理程序中生成的错误消息? [英] How do I see error messages generated in PowerShell event handlers?

查看:77
本文介绍了如何查看在PowerShell事件处理程序中生成的错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell错误通常在控制台中以红色文本显示。您可以使用 Write-Error'这是一个非终止错误消息示例。'

Normally PowerShell errors are shown in the console in red text. You can test this using Write-Error 'This is an example non-terminating error message.':

< img src = https://i.stack.imgur.com/ogmYO.png alt =红色文本错误消息截图>

脚本块内的错误但是,由事件调用的事件不会在控制台上显示相同的错误。该脚本演示了这种现象:

Errors inside the scriptblock called by an event, however, do not show the same errors on the console. This script demonstrates this phenomenon:

$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

请注意,第行错误这是错误消息。 在控制台中未显示。 PowerShell 似乎支持重定向输出的概念,但似乎更适合

Note that output from the line Write-Error "This is the error message." is not shown in the console. PowerShell seems to support the concept of redirecting output but it seems more geared toward redirecting to text files.

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

推荐答案

如果将块的全部内容包装到重定向到Write-Host的目录中,它将起作用。

If you wrap the entire contents of the block in a redirection to Write-Host, it works.

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

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

This uses the regular ("success") stream internally to keep track of all that stuff, then shoves it all to the actual console instead of throwing it away as I expect events normally do.

这篇关于如何查看在PowerShell事件处理程序中生成的错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆