首页 > 解决方案 > Powershell 运行空间:在从脚本块调用的 cmdlet 中形成的写入输出调用不显示为输出

问题描述

我直接在脚本块中的写入输出调用显示在运行空间输出中。但是我从该脚本块调用的 cmdlet 也会进行写入输出调用,但它们最终不会出现在运行空间输出中。

为了获得输出,我调用 PowerShell.EndInvoke(Job)。

下面是一些示例代码,相同的代码刚刚从 powershell 运行一些示例代码

非运行空间代码

Function Do-Output{
 [CmdletBinding()]
    Param(
    [int]$n)
    Process{ 
    write-output "Output from inside Do-Output($($n))"
    }
}
write-output "Output from before Do-Output(1) call"
Do-Output -n 1
write-output "Output from before Do-Output(2) call"
Do-Output -n 2
write-output "Output from before Do-Output(3) call"
Do-Output -n 3
write-output "Done"

非运行空间输出

Output from before Do-Output(1) call
Output from inside Do-Output(1)
Output from before Do-Output(2) call
Output from inside Do-Output(2)
Output from before Do-Output(3) call
Output from inside Do-Output(3)
Done

从运行空间运行的脚本块中的代码

Function Do-Output{
 [CmdletBinding()]
    Param(
    [int]$n)
    Process{ 
    write-output "Output from inside Do-Output($($n))"
    }
}


$Scriptblock = {

write-output "Output from before Do-Output(1) call"
Do-Output -n 1
write-output "Output from before Do-Output(2) call"
Do-Output -n 2
write-output "Output from before Do-Output(3) call"
Do-Output -n 3
write-output "Done"
}

从运行空间输出运行脚本块

来自 Do-Output cmdlet 内部的任何写入输出调用均未显示在输出中。

Output from before Do-Output(1) call
Output from before Do-Output(2) call
Output from before Do-Output(3) call
Done

我知道正在调用 cmdlet,就好像我在其中抛出异常一样,该异常就会出现。

标签: powershellrunspace

解决方案


我对此的解决方案是创建一个 ScriptBlock 包装器。这个脚本块包装器将在开始真正的脚本块之前开始一个脚本(我无法控制那个)。然后在包装脚本块中使用 Invoke-Command 启动真正的脚本块。

这有几个好处。然后我继续在我的模块中使用 write-host。
它还捕获详细输出。


推荐阅读