Powershell Start-job synchronous output

懵懂的女人 提交于 2019-12-05 23:35:40

问题


I have a powershell script that starts a job

start-job -scriptblock { 
  while($true) {
    echo "Running"
    Start-Sleep 2
  }
}

and then it continues executing the rest of the script.

That job, is kind of a monitoring one for the PID of that process.

I would like to synchronously print the PID every n seconds, without having to end the job.

For example, as the rest of the script is being executed, i would like to see output in my console.

Is something like that possible in powershell?

Thanks.


回答1:


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:

  • How to Get Windows PowerShell to Notify You When a Job is Complete
  • Manage Event Subscriptions with PowerShell - Hey, Scripting Guy! Blog


来源:https://stackoverflow.com/questions/20335659/powershell-start-job-synchronous-output

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