Question:
I have a powershell script that starts a job
1 2 3 4 5 6 7 |
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.
Answer:
Yes, you can use events:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$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: