PowerShell 接收作业输出到变量或文件而不是屏幕

Pie*_*Pie 5 powershell

我试图获取工作详细信息而不将数据输出到屏幕。但是,无论我尝试什么选项,作业日志总是会发送到控制台。关于如何将日志保存在变量或文件中而不将该数据输出到控制台的任何想法?

Receive-Job -Id $id -Keep -ErrorAction Continue > C:\Temp\Transcript-$VM.txt

$info = Receive-Job -Id $id -Keep -ErrorAction Continue
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 4

您声明您的作业使用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
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于已知的错误,您仍然会获得控制台输出该错误仍然存​​在于 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
Run Code Online (Sandbox Code Playgroud)

请注意,我使用完整路径作为重定向目标,因为不幸的是,在后台作业中执行的 PowerShell 脚本块的 v6 版本中,不会继承调用者的当前位置。这将在 PowerShell Core v7.0 中发生变化。