Skip to content

Instantly share code, notes, and snippets.

@proxb
Last active December 16, 2022 01:54
Show Gist options
  • Save proxb/a9a70d6f08e6c25115d7dea16318bf80 to your computer and use it in GitHub Desktop.
Save proxb/a9a70d6f08e6c25115d7dea16318bf80 to your computer and use it in GitHub Desktop.
Sending data from PSJob to main PowerShell Console while job is still running
#Register the event subscription for the forwarded event
Register-EngineEvent -SourceIdentifier This.Nothing -Action {
Write-Host ("Date: {0}" -f $event.messagedata) -BackgroundColor Black -ForegroundColor Yellow
}
Start-Job -Name TestJob -ScriptBlock {
While ($True) {
Register-EngineEvent -SourceIdentifier This.Nothing -Forward
Start-Sleep -seconds 5
New-Event -SourceIdentifier This.Nothing -Message ("[{0}] From PSJob" -f (Get-Date))
}
}
#Let it run for several seconds to see the date is updated, then run the commands on like 15,16 to halt the job
Get-Event | UnregisterEvent
Get-Job | Remove-Job -Force
##--------------------------------------------------------------------------------------------------------------
##Objects can also be passed thru to the console, but can't be displayed without writing them out as a stream
##--------------------------------------------------------------------------------------------------------------
#Register the event subscription for the forwarded event
Register-EngineEvent -SourceIdentifier This.Nothing -Action {
Write-Host ($event.messagedata | Out-String) -BackgroundColor Black -ForegroundColor Yellow
}
Start-Job -Name TestJob -ScriptBlock {
While ($True) {
Register-EngineEvent -SourceIdentifier This.Nothing -Forward
Start-Sleep -seconds 5
New-Event -SourceIdentifier This.Nothing -Message ([pscustomobject]@{Test=(get-Date)})
}
}
#Let it run for several seconds to see the date is updated, then run the commands on like 34,35 to halt the job
Get-Event | UnregisterEvent
Get-Job | Remove-Job -Force
@a-dimas
Copy link

a-dimas commented Feb 15, 2022

Typo in lines 15 and 34: it's Unregister-Event

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment