【问题标题】:How to combine PowerShell runspace stderr, stdout etc into a single stream如何将 PowerShell 运行空间 stderr、stdout 等组合成一个流
【发布时间】:2020-04-26 04:45:53
【问题描述】:

我正在寻找相当于运行作业时的 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 task runspace


    【解决方案1】:

    要在使用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) 以外的流的输出对象具有反映源流的统一类型,因此您可以检查每个输出对象的类型以推断它来自哪个流 - 详情请见this answer

    有关 PowerShell 的 6 个输出流的详细信息,请运行 Get-Help about_Redirection

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 2019-04-23
      • 1970-01-01
      • 2011-05-05
      • 2015-04-20
      • 1970-01-01
      • 2015-05-20
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多