runspace:EndInvoke()无法返回所有脚本块输出,只返回最后一个异常



脚本块

$sb = {
write-output "Testing 1"
write-output "Testing 2"
throw " Exception in sb"
}

调用EndInvoke()只返回以下内容。在某些情况下,我的运行空间任务长达数小时。除了最后一个异常,我不能丢失所有输出。我无法控制脚本块,因为它们被传递到我的cmdlet中。

我该如何解决?

Exception calling "EndInvoke" with "1" argument(s): " Exception in sb"
At line:1 char:1
+ $j.PowerShell.EndInvoke($j.Job)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : RuntimeException

当您呼叫EndInvoke()时,您已经太迟了。没有办法从输出流接收数据,因为所有的数据都被丢弃了,你只能得到抛出的异常消息。相反,您必须更改执行初始BeginInvoke()调用的方式,以便捕获输出。

使用重载的BeginInvoke(TInput,TOutput)调用,您既可以传递输入命令(如果需要,或者为空(,也必须为要存储的输出提供缓冲区(类型为System.Management.Automation.PSDataCollection[psobject](。所以你的代码看起来是这样的:

$sb = {
write-output "Testing 1"
write-output "Testing 2"
throw " Exception in sb"
}
$PowerShell = [powershell]::Create()
[void]$PowerShell.AddScript($sb)
$InputObject = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$OutputObject = New-Object 'System.Management.Automation.PSDataCollection[psobject]'
$Handle = $PowerShell.BeginInvoke($InputObject,$OutputObject)

调用EndInvoke()会给您错误消息:

PS C:> $PowerShell.EndInvoke($Handle)
Exception calling "EndInvoke" with "1" argument(s): " Exception in sb"
At line:1 char:1
+ $PowerShell.EndInvoke($Handle)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : RuntimeException

但输出存储在$OutputObject缓冲区中:

PS C:> $InputObject
PS C:> $OutputObject
Testing 1
Testing 2

最新更新