Search code examples
powershellscriptingstart-job

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.


Solution

  • 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: