How do I Start a job of a function i just defined?

How do I Start a job of a function i just defined?

function FOO { write-host "HEY" } Start-Job -ScriptBlock { FOO } |
Receive-Job

Receive-Job: The term 'FOO' is not recognized as the name of cmdlet,
function ,script file or operable program.

What do I do? Thanks.


Solution 1:

As @Shay points out, FOO needs to be defined for the job. Another way to do this is to use the -InitializationScript parameter to prepare the session.

For your example:

$functions = {
    function FOO { write-host "HEY" }
}

Start-Job -InitializationScript $functions -ScriptBlock {FOO}|
    Wait-Job| Receive-Job

This can be useful if you want to use the same functions for different jobs.

Solution 2:

@Rynant's suggestion of InitializationScript is great

I thought the purpose of (script) blocks is so that you can pass them around. So depending on how you are doing it, I would say go for:

$FOO = {write-host "HEY"}

Start-Job -ScriptBlock $FOO | wait-job |Receive-Job

Of course you can parameterize script blocks as well:

$foo = {param($bar) write-host $bar}

Start-Job -ScriptBlock $foo -ArgumentList "HEY" | wait-job | receive-job