Automatically pulling data from a PowerShell job while running Automatically pulling data from a PowerShell job while running powershell powershell

Automatically pulling data from a PowerShell job while running


You can return data from a job by raising an event and forwarding it back to the local session.

Here is an example:

 $job = Start-Job -Name "ReturnMessage" -ScriptBlock {     # forward events named "MyNewMessage" back to job owner     # this even works across machines     Register-EngineEvent -SourceIdentifier MyNewMessage -Forward     while($true) {         sleep 2         $i++         $message = "This is message $i."         # raise a new progress event, assigning to $null to prevent         # it ending up in the job's output stream         $null = New-Event -SourceIdentifier MyNewMessage -MessageData $message     } }$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {    Write-Host $event.MessageData -ForegroundColor Green}<# Run this to stop job and event listner$job,$event| Stop-Job -PassThru| Remove-Job#>

Note that you can still type at the prompt while the job is running. Execute the code in the block comments to stop the job and event listner.