Search code examples
powershelludpjobs

Automatically pulling data from a PowerShell job while running


While trying to do something quite possibly beyond the means of PowerShell I seem to have ran into a brick wall. I have a main form script, which orchestrates most of my functions but I need another script to open a listener (system.Net.Sockets.Udpclient.Receive) and keep feeding in information to a textbox in the main form throughout the entire program's running. For the life of me I can't get around this daft non-child environment that jobs suffer from; no dot sourcing, no global scoped variables, nothing. I can put an object-listener on it for statechanged to completion and then open another listener and try and bodge this way but it will get very messy and unreliable.

As a workaround I would love a TCP/UDP listener which doesn't hang the application for a response, an event to pull on hasmoredata or a way of updatign the textbox in the main script from within the job.


Solution

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