bie*_*ski 2 powershell task runspace
我正在寻找运行作业时与 PowerShell 管道重定向 *>&1 等效的内容。
我大致这样运行作业:
$Instance = [PowerShell]::Create()
$Instance.AddScript($CommandList)
$Result = $Instance.BeginInvoke()
$Instance.EndInvoke($Result)
Run Code Online (Sandbox Code Playgroud)
问题是输出被分成多个流,要报告它我必须这样做:
$Instance.Streams.Debug
$Instance.Streams.Error
$Instance.Streams.Information
Run Code Online (Sandbox Code Playgroud)
这会按类型对消息进行分组,而不是将它们交错排列,因此没有好的方法可以判断在执行过程中的何处抛出了给定的错误。如果将它们组合起来,错误将立即出现在相关的 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.
Run Code Online (Sandbox Code Playgroud)
由于除了成功流 ( 1) 之外的流中的输出对象具有反映原始流的统一类型,因此您可以检查每个输出对象的类型以推断它来自哪个流 - 有关详细信息,请参阅此答案。
有关 PowerShell 的 6 个输出流的更多信息,请运行Get-Help about_Redirection。
| 归档时间: |
|
| 查看次数: |
672 次 |
| 最近记录: |