Powershell Start-job synchronous output
Asked Answered
A

1

7

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.

Adaurd answered 2/12, 2013 at 18:52 Comment(0)
S
13

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:

Sidonius answered 2/12, 2013 at 20:16 Comment(2)
Thank you Neolisk. Great answer indeed. I didn't know about events in powershell. That's a good start to know about it. Thanks a lot again.Adaurd
Fantastic! Events are awesome.Indreetloire

© 2022 - 2024 — McMap. All rights reserved.