2

I have the following functions (these are simplified examples)

function a {return 2}
function b {$a=a; return $a+2}
function c {$a=a; return $a*10}

When I run the following codes

Start-Job -ScriptBlock $Function:b -Name "test"

Receive-Job -Name "test"

It shows me this error:

The term 'a' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Any idea on how to start a function as a job while that function calls another function? Each function needs to be used independently as well (explained in Edit 1). In short, I need to be able to run function c (as a job) too.

Edit 1: Here provides a solution but if I do so, I can not run functions independently. It is almost the same solution provided by @TheIncorrigible1.

Alin
  • 350
  • 2
  • 13

1 Answers1

3

When you pass a scriptblock to Start-Job, it's no longer part of your scope; it cannot see the external definitions. You would need to nest it inside your function to be applicable:

function b {
    function a { return 2 }

    $a = a
    return $a + 2
}

Start-Job -ScriptBlock $Function:b -Name test
Receive-Job -Name test
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
  • +1. I have seen almost the same approach but what if I want to use `function a` in another part of the script. It is my issue because I have some functions that I use frequently such as `Logger` or `Validation` that I use in many functions. – Alin Nov 13 '19 at 15:33
  • 2
    @Alin The problem is `Start-Job` starts up a new session so nothing is available without it explicitly being so. You could change your function to take arguments that are functions to invoke and pass them through using `Start-Job` with `ArgumentList`. Alternatively, you use the `FilePath` parameterset. – Maximilian Burszley Nov 13 '19 at 15:38
  • I see. Is there any way that I be able to run `function a` separately. I mean is it possible to have a scriptblock of different functions as it is defined [here](https://stackoverflow.com/a/7162842/4741225) and run just one of the functions? – Alin Nov 14 '19 at 08:18
  • @Alin Yes, you can also use the `InitializationScript` parameter. – Maximilian Burszley Nov 14 '19 at 13:53
  • Is there such a thing as a JOB system for powershell that isn't insane and stupid and useless by default? – Warren P Jun 17 '21 at 18:57