Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Start-job synchronous output

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.

like image 806
nikkatsa Avatar asked Dec 02 '13 18:12

nikkatsa


1 Answers

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
like image 101
Neolisk Avatar answered Oct 10 '22 06:10

Neolisk