Automatically pulling data from a PowerShell job while running

前提是你 提交于 2019-12-03 08:38:53

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!