Background jobs are started in a separate process, so jobs created using Start-Job cannot interact with functions unless you include them in $scriptblock .
Even if you included the function in $scripblock , Write-Host does not print its contents to the console until you use Get-Job | Receive-Job Get-Job | Receive-Job to get the result of the job.
EDIT . The problem is that your DisplayMessage function is in the local script -scope, while your event handler is running in a different parent scope (e.g. global, which is the session scope), so it cannot find your function. If you create this function in the global area and call it from the global area, it will work.
I modified your script to do it now. I also modified the script block and unregistered events when the script is executed, so you will not receive 10x messages when the script is run multiple times :-)
Untitled1.ps1
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
Test
PS > .\Untitled1.ps1 Processing Starts Starting work 1 Starting work 2 Ending work 1 Ending work 2 Starting work 3 Ending work 3 Processing Ends
source share