运行作业时,我正在寻找等效的PowerShell管道重定向*>&1。
我大致像这样运行作业:
$Instance = [PowerShell]::Create()
$Instance.AddScript($CommandList)
$Result = $Instance.BeginInvoke()
$Instance.EndInvoke($Result)
麻烦的是输出被分为多个流,要报告它,我必须这样做:
$Instance.Streams.Debug
$Instance.Streams.Error
$Instance.Streams.Information
这按类型对消息进行分组,而不是对消息进行交织,因此,没有一种好的方法可以判断执行过程中在何处抛出了给定的错误。如果将它们合并,则错误将在相关的Write-Host语句之后立即出现。
似乎有5个流(调试,错误,信息,进度,详细和警告),我想将它们全部组合在一起,尽管简单地将错误和信息组合起来将是巨大的进步。
我环顾了$ Instance对象,并尝试在InitialSessionState下找到要传递给Create()的东西,但没有明显的展现。
最佳答案
要在使用PowerShell SDK时按输出顺序访问所有流的输出,还必须使用*>&1
:
$Instance = [PowerShell]::Create()
# Example commands that write to streams 1-3.
$CommandList = 'Write-Output 1; Write-Error 2; Write-Warning 3'
# Wrap the commands in a script block (`{...}`) and call it using
# `&`, the call operator, which allows you to apply redirection `*>&1`
$null = $Instance.AddScript('& {' + $CommandList + '} *>&1')
$Result = $Instance.BeginInvoke()
$Instance.EndInvoke($Result) # Returns output merged across all streams.
由于成功流(
1
)以外的流的输出对象具有反射(reflect)源流的统一类型,因此您可以检查每个输出对象的类型以推断出它来自什么流-有关详细信息,请参见this answer。
有关PowerShell的6个输出流的更多信息,请运行
Get-Help about_Redirection
。
关于powershell - 如何将PowerShell Runspace stderr,stdout等合并到单个流中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649401/