0

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?

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
red888
  • 27,709
  • 55
  • 204
  • 392

1 Answers1

0

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 }  
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
  • I'm confused, I have a bunch of functions in separate files dot sourced in one main file how would I call the dot sourced functions in the main file? – red888 Aug 25 '16 at 04:51
  • 1
    You will have to import / dot-source the necessary functions again in that job .e.g via the init script block as shown above – DAXaholic Aug 25 '16 at 05:03
  • Ah I'll try that, is there a difference between dot sourcing and doing ${function:myfunc} inside the script block? – red888 Aug 25 '16 at 05:06
  • 1
    Yeah that is quite different - `${function:myfunc}`actually gets you the function object (script block) of `myfunc` itself whereas dot-sourcing a script file essentially processes the script file's contents in your scope which may define - among others - the function `myfunc`. So both are fundamentally different things - maybe I also misunderstood your question :) – DAXaholic Aug 25 '16 at 05:14