function F2([String]$var2)
{
.........
.........
}
function F1([String]$var1)
{
.........
F2 $
What a Start-Job does is to create a separate thread in the backend, initial another default Powershell session in the thread and run the commands passed in with the parameter -ScriptBlock.
The session in the new thread is a fresh session, it doesn't have any non-default module, variable or function loaded in. It has its own variable scoping and life cycle. So I'm not sure if it's possible to let it use the function defined in the default session, but at least it's not easy as I can see.
One workaround I can provide is to use the parameter -InitializationScript to define the function F2 like below
function F1([String]$var1)
{
.........
F2 $var2
.........
}
..................
..................
while ($i -le $count)
{
F1 "dir$i"
Start-Job -ScriptBlock ${function:F1} -ArgumentList @($i) -InitializationScript {function F2([String]$var2){.........}}
$i = $i + 1
}
Alternatively, if you have to define multiple functions like F1 that needs to call F2 and want to somehow reuse the code of F2's definition. We can create a ScriptBlock object for F2
$InitializationScript = [ScriptBlock]::Create('function F2([String]$var2){.........}')
function F1([String]$var1)
{
.........
F2 $var2
.........
}
..................
..................
while ($i -le $count)
{
F1 "dir$i"
Start-Job -ScriptBlock ${function:F1} -ArgumentList @($i) -InitializationScript $InitializationScript
$i = $i + 1
}
Best regards,
Dong