powershell - 如何捕获作业的信息输出流?
问题描述
如果我开始一项工作,并且该工作将消息输出到信息流(或与此相关的任何流),我如何将其捕获到变量中,或者在我收到工作后简单地输出它?
$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
参数,但我不明白如何使用它,或者它是否与我的问题相关。我已经尝试了几种重定向方法,但我对流方面的工作一无所知。
这个问题给了我一些提示,但还不足以理解。
这个问题非常相似,但似乎在信息流存在之前就已经被问过了。除非必要,否则我宁愿不使用 Transcripts;我觉得应该有更好的方法。
一些答案引用了对象的ChildJobs
、Output
和Information
属性Job
,但我很难理解如何使用它们,因为它们在我的简单测试中始终为空。
谢谢你的时间。
解决了
感谢@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
解决方案
不同的 Streams 分别存储在 job 对象中:
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
在上面的示例中,它将返回“某物”,引用作业中的命令。
参考这里还有一些其他的好信息。
推荐阅读
- javascript - 如何将数据对象重组为对象数组?
- php - 在简单的 html dom 中按类和 id 选择在谷歌搜索中不起作用
- python - 如何从python selenium中的只读框中复制文本
- testing - SpecFlow 功能测试未添加到 Visual Studio 2019 测试资源管理器窗口
- deno - Deno 属性 'utime' 在类型 'typeof Deno' 上不存在。等待 Deno.utime(dest, statInfo.atime, statInfo.mtime);
- telegram - 电报机器人错误:我无法发送其用户名
- c# - 执行三元运算符或将枚举转换为浮点数哪个更快?
- django - Django 月度用户账单记录
- python - 使用 python 和 mysql 从数据库中的一组值中更新最后输入的值
- python - How to get a person's age from his date of birth in Odoo?