powershell - 如何将PowerShell Runspace stderr,stdout等合并到单个流中

标签 powershell task runspace

运行作业时,我正在寻找等效的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/

相关文章:

c - 任务分解

c# - 用于自动化的 SSIS C# 脚本任务

c# - 使用 C# 6.0 代码的 MSBuild 命令行无法构建

.net - C# .NET 任务 : How to get notification when multiple tasks have completed

powershell - 为什么在 PowerShell 中的 for 循环中省略变量会导致无限循环?

powershell - PowerShell:RunSpace.SessionStateProxy.SetVariable未设置变量

带 RunspacePool 的 C# PowerShell - 如何导入 Exchange Cmdlet,如 Get-Mailbox?

powershell - 在 .NetCore 应用程序中运行 PS 时出错 - 无法执行操作,因为运行空间不在 'Opened' 状态。运行空间的当前状态是 'Broken'

powershell - 如何从列表中异步调用多个 URL

powershell - 如何使用PowerShell动态创建文件夹?