运行空间: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