Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Background jobs are run in a seperate process, so the jobs you create with <code>Start-Job</code> can not interact with functions unless you include them in the <code>$scriptblock</code>.</p> <p>Even if you included the function in the <code>$scripblock</code>, <code>Write-Host</code> would not output it's content to the console until you used <code>Get-Job | Receive-Job</code> to recieve the jobs result.</p> <p><strong>EDIT</strong> The problem is that your <code>DisplayMessage</code> function is in a local script-scope while your eventhandler runs in a different parent scope(like global which is the session scope), so it can't find your function. If you create the function in the global scope and call it from the global scope, it will work. </p> <p>I've modified your script to do this now. I've also modified to scriptblock and unregistered the events when the script is done so you won't get 10x messages when you run the script multiple times :-)</p> <p>Untitled1.ps1</p> <pre><code>function DoWork { $event = Register-EngineEvent -SourceIdentifier NewMessage -Action { global:DisplayMessage $event.MessageData } $scriptBlock = { Register-EngineEvent -SourceIdentifier NewMessage -Forward $message = "Starting work $args" $null = New-Event -SourceIdentifier NewMessage -MessageData $message ### DO SOME WORK HERE ### $message = "Ending work $args" $null = New-Event -SourceIdentifier NewMessage -MessageData $message Unregister-Event -SourceIdentifier NewMessage } DisplayMessage("Processing Starts") $array = @(1,2,3) foreach ($a in $array) { Start-Job -Name "DoActualWork" $ScriptBlock -ArgumentList $a | Out-Null } #$jobs = Get-Job -Name "DoActualWork" While (Get-Job -Name "DoActualWork" | where { $_.State -eq "Running" } ) { Start-Sleep 1 } DisplayMessage("Processing Ends") #Get-Job -Name "DoActualWork" | Receive-Job } function global:DisplayMessage([string]$message) { Write-Host $message -ForegroundColor Red } DoWork Get-EventSubscriber | Unregister-Event </code></pre> <p>Test</p> <pre><code>PS &gt; .\Untitled1.ps1 Processing Starts Starting work 1 Starting work 2 Ending work 1 Ending work 2 Starting work 3 Ending work 3 Processing Ends </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload