简体   繁体   English

为什么在 powershell 作业中运行时,Write-Host 不起作用?

[英]Why does Write-Host not work when run in a powershell job?

Sorry if I'm being a dumb powershell noob, but what's wrong with jobs apparently being unable to write to the terminal?对不起,如果我是一个愚蠢的 powershell 菜鸟,但是工作显然无法写入终端有什么问题? And how can I fix that?我该如何解决?

# test.ps1
function myjob {
    Write-Host "Hello, World!" # doesn't show
}
Start-Job -Name MyJob -ScriptBlock ${function:myjob}
Wait-Job MyJob
Remove-Job MyJob

It sounds like you're trying to use Write-Host to directly, synchronously write to the console (terminal) from a background job.听起来您正在尝试使用Write-Host从后台作业直接同步写入控制台(终端)。

However, PowerShell jobs do not allow direct access to the caller's console .但是, PowerShell 作业不允许直接访问调用者的控制台 Any output - even to the PowerShell host (which in foreground use is the console, if run in one) is routed through PowerShell's system of output streams (see the conceptual about_Redirection help topic).任何output - 甚至到 PowerShell主机(在前台使用是控制台,如果在一个中运行)都通过 PowerShell 的 output 系统进行路由(请参阅关于_Redirection概念帮助主题)流。

Therefore, you always need the Receive-Job cmdlet in order to receive output from a PowerShell job:因此,始终需要Receive-Job cmdlet 才能从 PowerShell 作业接收 output

$null = Start-Job -Name MyJob -ScriptBlock { Write-Host "Hello, World!" } 
Receive-Job -Wait -AutoRemoveJob -Name  MyJob

Caveat :警告

  • In foreground use, Write-Host output - even though primarily designed to go to the host (console) - can be redirected or captured via the information stream (whose number is 6 , available in PSv5+);前台使用中, Write-Host output - 尽管主要设计为 go 到主机(控制台) - 可以通过信息 ZF7B44CFAFD5C52223D5498196C8A2E 6或捕获(谁是号码) eg:例如:

     # OK - no output Write-Host 'silence me' 6>$null
  • Write-Host output received via a (child-process-based) background job , however, can not be redirected or captured, as of PowerShell 7.2.1:但是,从 PowerShell 7.2.1 开始,无法重定向或捕获通过(基于子进程的)后台作业接收的Write-Host output:

     #.! `silence me` still prints. Start-Job { Write-Host 'silence me' } | Receive-Job -Wait -AutoRemoveJob 6>$null
    • By contrast, it can be redirected/captured when using a (generally preferable) thread -based background job (as opposed to a child-process -based background job), via Start-ThreadJob :相比之下,当使用(通常更可取的)基于线程的后台作业(与基于子进程的后台作业相反)时,可以通过Start-ThreadJob重定向/捕获它:

       # OK - no output Start-ThreadJob { Write-Host 'silence me' } | Receive-Job -Wait -AutoRemoveJob 6>$null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM