How to use the same powershell function in the main code and a background process

StackOverflow https://stackoverflow.com/questions/12022497

  •  27-06-2021
  •  | 
  •  

質問

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?

役に立ちましたか?

解決

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

$add = { function add($a,$b) { return $a+$b } }
. $add
add 2 4
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top