Question

I want to use the same function in a background process that I use in the body of my main code.

If I write it this way, the "add" function works for the background process but I cannot use it in the main code.

$add = { function add($a,$b) { return $a+$b } }
$job = Start-Job -Name "test" -ArgumentList @(2,4) -InitializationScript $add -ScriptBlock { return add $args[0] $args[1] }
sleep 1
Receive-Job -Name "test"
Remove-Job -Name "test" -force
add 2 4

If I remove the {} around the "add" function definition, it works for the main body, but not for the background process.

$add = function add($a,$b) { return $a+$b }
$job = Start-Job -Name "test" -ArgumentList @(2,4) -InitializationScript $add -ScriptBlock { return add $args[0] $args[1] }
sleep 1
Receive-Job -Name "test"
Remove-Job -Name "test" -force
add 2 4

How can I use my function in both the background process and the main code?

Was it helpful?

Solution

Dot-source your "library" scriptblock in your main code.

$add = { function add($a,$b) { return $a+$b } }
. $add
add 2 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top