我想获取工作详细信息,但不希望将数据输出到屏幕。无论我尝试哪个选项,作业日志总是发送到控制台。有没有办法在不输出到控制台的情况下将日志保存在变量或文件中?
Receive-Job -Id $id -Keep -ErrorAction Continue > C:\Temp\Transcript-$VM.txt
$info = Receive-Job -Id $id -Keep -ErrorAction Continue
我想获取工作详细信息,但不希望将数据输出到屏幕。无论我尝试哪个选项,作业日志总是发送到控制台。有没有办法在不输出到控制台的情况下将日志保存在变量或文件中?
Receive-Job -Id $id -Keep -ErrorAction Continue > C:\Temp\Transcript-$VM.txt
$info = Receive-Job -Id $id -Keep -ErrorAction Continue
您提到您的工作使用Write-Host
输出,并且您正在运行Windows PowerShell v5.1。
为了还能够捕获Write-Host
输出 - 在v5+中将被发送到信息流(流号为6
) - 请使用重定向 6>&1
:
# Capture both success output and information-stream output
# (Write-Host) output in $info.
$info = Receive-Job -Id $id -Keep -ErrorAction Continue 6>&1
很不幸的是,由于已知的 错误,即使在PowerShell Core 7.0.0-preview.5中该错误仍然存在,您仍将得到控制台输出的。
捕获所有重定向*>&1
通常通过成功输出流路由所有流。
很不幸,由于上面链接的错误,使用后台作业或远程时以下流不能被完全捕获或重定向::
4
)5
)唯一的解决方法是在作业内部捕获流并将其保存到文件,然后稍后从调用者中访问这些文件。
当然,这需要您对作业的创建方式有控制权。
一个简化的例子:
# Redirect all output streams *inside* the job to a file...
Start-Job {
& {
# The job's commands go here.
# Note that for any *verbose* output to be captured,
# verbose output must explicitly turned on, such as with
# the -Verbose common parameter here.
# You can also set $VerbosePreference = 'Continue', which
# cmdlets (including advanced functions/scripts) will honor.
'success'; write-verbose -Verbose 'verbose'; write-host 'host'
} *> $HOME/out.txt
} | Receive-Job -Wait -AutoRemove
# ... then read the resulting file.
Get-Content $HOME/out.txt
Receive-Job -Id $id -Keep -ErrorAction Continue | Set-Content 'C:\Temp\Transcript-$VM.txt'
>
在幕后确实涉及到管道;它就像隐式使用了 | Out-File
,因此你所建议的基本上不会产生差异。 - mklement0
Write-Host
或Out-Host
语句。如果有的话,您应该将其删除。如果您使用 PowerShell v5 或更高版本,则还可以在脚本块中设置$InformationPreference
变量为'Ignore'
,但这可能会产生意想不到的后果。-InformationAction 'Ignore'
在Write-Host
上执行相同的操作,但只针对特定命令,并且不影响环境设置。 - AdminOfThings