red888 red888 - 3 months ago 14
PowerShell Question

not getting output from receive job

The variable $var is blank when I run this script:

function FOO { write-output "HEY" }

$var = Start-Job -ScriptBlock { ${function:FOO} } | Wait-Job | Receive-Job

$var


How do I get output from receive-job?

Answer

Start-Job spawns a new PowerShell instance in the background and as such has no knowledge of your function FOO which is defined in your initial instance

There is an additional parameter InitializationScript which is called upfront executing your script block in the new instance which you can use to define FOO like so

$var = Start-Job -InitializationScript { function FOO { write-output "HEY" } } -ScriptBlock ...  

BTW: I guess you want to execute the function instead of getting the function object itself so you may want to change your script block to this

-ScriptBlock { FOO }  
Comments