Powershell Start-job synchronous output

六眼飞鱼酱① 提交于 2019-12-04 04:10:29
Neolisk

Yes, you can use events:

$job = Start-Job -ScriptBlock { 
  while($true) {
    Register-EngineEvent -SourceIdentifier MyNewMessage -Forward
    Start-Sleep -Seconds 3
    $null = New-Event -SourceIdentifier MyNewMessage -MessageData "Pingback from job."
  }
}

$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {
  Write-Host $event.MessageData;
}

for($i=0; $i -lt 10; $i++) {
  Start-Sleep -Seconds 1
  Write-Host "Pingback from main."
}

$job,$event| Stop-Job -PassThru| Remove-Job #stop the job and event listener

Credit goes to this answer. Other useful links:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!