简体   繁体   English

运行空间:EndInvoke() 未能返回所有脚本块 output,只有最后一个异常

[英]runspace: EndInvoke() fails to return all the scriptblocks output , only the last exception

The script block脚本块

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

Calling EndInvoke() only returns the below.调用EndInvoke()仅返回以下内容。 My runspace tasks are in some case hours long.在某些情况下,我的运行空间任务长达数小时。 I can not lose all the output except the last exception.除了最后一个例外,我不能丢失所有 output。 I do not have control over the script blocks as they get passed into my cmdlets.当脚本块被传递到我的 cmdlet 时,我无法控制它们。

How do I resolve that?我该如何解决?

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

By the time you call EndInvoke() , you are already too late.当您调用EndInvoke()时,您已经为时已晚。 There is no way to receive the data from the output stream as all that data is discarded and the only thing you will get is the thrown exception message.无法从 output stream 接收数据,因为所有数据都被丢弃,您唯一会得到的是抛出的异常消息。 Instead, you have to change how you do your initial BeginInvoke() call to allow you to capture the output.相反,您必须更改执行初始BeginInvoke()调用的方式,以允许您捕获 output。

Using an overloaded BeginInvoke(TInput,TOutput) call, you can both pass your input commands (if needed, or blank), as well as you have to supply a buffer for the output to be stored (of type System.Management.Automation.PSDataCollection[psobject] ).使用重载的BeginInvoke(TInput,TOutput)调用,您既可以传递输入命令(如果需要,也可以传递输入命令),并且必须为要存储的 output 提供缓冲区(类型为System.Management.Automation.PSDataCollection[psobject] )。 So your code looks like this:所以你的代码看起来像这样:

$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)

Calling EndInvoke() will give you the error message:调用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

But the output is stored in the $OutputObject buffer:但是 output 存储在$OutputObject缓冲区中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM