How to pass arguments to a function that is called from a Start-Job scriptblock

The following code works, but I don’t understand how to pass arguments to it.

I think the complications might be because of $Export_Functions, which I don’t fully understand how works.

Is $var supposed to be inside $Export_Functions somewhere?

Function Job1 ($variable) { Write-Output "Start job1" Write-Output $variable # is NULL, should be "test" Write-Output $args[0] # I want this to output "test" Start-Sleep -Seconds 1 Write-Output "Finished job1" } $Var = "test" #https://stackoverflow.com/a/39857287 $Export_Functions = [scriptblock]::Create(@" Function Job1 { $function:Job1 } "@) $Job = Start-Job -InitializationScript $Export_Functions -ScriptBlock { Job1 } -ArgumentList $Var | Wait-Job | Receive-Job #$Job = Start-Job -InitializationScript $Export_Functions -ScriptBlock {param($Var) { Job1 }} -ArgumentList $Var | Wait-Job | Receive-Job $Job 

Keep in mind I’m trying both the $variable parameter and args[], I only need one or the other to work.

As seen here, passing arguments is easier when not dealing with functions.

submitted by /u/nikkle2
[link] [comments]

Leave a Reply