如何捕获作业的信息输出流?

How can I capture the Information output stream of a Job?

如果我开始一项工作,并且该工作将消息输出到信息流(或与此相关的任何流),我如何将其捕获到变量中,或者在收到工作后简单地输出它?

$script = {
    [PSCustomObject]@{ "CoolProperty" = "CoolValue" }
    Write-Information "Returning a cool object" -InformationAction "Continue"
}

Start-Job -Name "test" -ScriptBlock $script | Out-Null
Wait-Job -Name "test" | Out-Null
$result = Receive-Job -Name "test" 6>&1
Remove-Job -Name "test"

以上代码会输出

Returning a cool object

到控制台,但我想捕获它并将其输出到我用于整个脚本的日志文件,例如:

$JustTheInfoStreamFromJob | Out-File "c:\file.log" -Append

我不想记录捕获的 $result,因为它还包含输出流(即对象)。我只想记录信息流。所以我正在寻找一种方法将其分开。

我看到有一个 -InformationVariable 参数,但我不明白如何使用它,或者它是否与我的问题相关。我已经尝试了几种重定向方法,但对于流,我几乎不知道自己在做什么。

这个question给了我一些提示,但还不够理解。

这个 question 非常相似,但似乎在信息流存在之前就已经被问过。除非必要,否则我宁愿不使用 Transcripts;我觉得应该有更好的方法。

一些答案引用了 Job 对象的 ChildJobsOutputInformation 属性,但我很难理解如何使用它们,因为它们在我的简单测试中始终为 null。

感谢您的宝贵时间。

已解决

感谢@Santiago Squarzon 和@Steven 提供两种不同的工作解决方案:

Remove-Job "test"
$script = {
    [PSCustomObject]@{ "CoolProperty" = "CoolValue" }
    Write-Information "Returning a cool object"
}

Start-Job -Name "test" -ScriptBlock $script | Out-Null
$job = Get-Job -Name "test" -IncludeChildJob # Steven's solution
$job | Wait-Job | Out-Null
$info = $job.Information # Steven's solution
$result = Receive-Job -Name "test" -InformationVariable info2 # Santiago Squarzon's solution
Remove-Job -Name "test"

$result
"---"
$info
"---"
$info2

这允许我分别捕获作业的输出和作业的信息流(两种不同的方式):

CoolProperty RunspaceId
------------ ----------
CoolValue    f49c78bd-eda3-4c47-a6bc-d89a146618e9
---
Returning a cool object
---
Returning a cool object

不同的流分别存储在作业对象中:

State         : Completed
HasMoreData   : True
StatusMessage :
Location      : localhost
Command       :  Write-Information "something"
JobStateInfo  : Completed
Finished      : System.Threading.ManualResetEvent
InstanceId    : ff5d1155-aca1-40fa-8e4e-dce6b87c709c
Id            : 2
Name          : test
ChildJobs     : {Job3}
PSBeginTime   : 4/2/2021 9:41:26 PM
PSEndTime     : 4/2/2021 9:41:26 PM
PSJobTypeName : BackgroundJob
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
Information   : {}

注意子 Job,但您可以通过以下方式获取信息流:

(Get-Job -Name test -IncludeChildJob).Information

在上面的示例中,它将 return“某事”,引用作业中的命令。

参考 here 还有其他一些有用的信息。