I want to use background jobs in Powershell.
How to make variables evaluated at the moment of ScriptBlock definition?
$v1 = "123"
$v2 = "asdf"
$sb = {
Write-Host "Values are: $v1, $v2"
}
$job = Start-Job -ScriptBlock $sb
$job | Wait-Job | Receive-Job
$job | Remove-Job
I get printed empty values of $v1 and $v2. How can I have them evaluated in (passed to) the scriptblock and so to the background job?
The simplest solution (which requires V3 or greater) looks like this:
You can think of $using as working roughly like an explicit param() block and passing -ArgumentList, only PowerShell handles that for you automatically.
I'm not at a computer to validate, but this should work:
I'll double check this when I get into work.
Declare the values as parameters in the script block, then pass them in using
-ArgumentList
One way is to use the [scriptblock]::create method to create the script block from an expanadable string using local variables:
Another method is to set variables in the InitializationScript:
A third option is to use the -Argumentlist parameter: