Powershell - how to pre-evaluate variables in a scriptblock for Start-Job Powershell - how to pre-evaluate variables in a scriptblock for Start-Job powershell powershell

Powershell - how to pre-evaluate variables in a scriptblock for Start-Job


One way is to use the [scriptblock]::create method to create the script block from an expanadable string using local variables:

$v1 = "123"$v2 = "asdf"$sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")$job = Start-Job -ScriptBlock $sb

Another method is to set variables in the InitializationScript:

$Init_Script = {$v1 = "123"$v2 = "asdf"}$sb = {    Write-Host "Values are: $v1, $v2"}$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb 

A third option is to use the -Argumentlist parameter:

$v1 = "123"$v2 = "asdf"$sb = {    Write-Host "Values are: $($args[0]), $($args[1])"}$job = Start-Job  -ScriptBlock $sb -ArgumentList $v1,$v2


The simplest solution (which requires V3 or greater) looks like this:

$v1 = "123"$v2 = "asdf"$sb = {     Write-Host "Values are: $using:v1, $using:v2"}$job = Start-Job -ScriptBlock $sb

You can think of $using as working roughly like an explicit param() block and passing -ArgumentList, only PowerShell handles that for you automatically.


Declare the values as parameters in the script block, then pass them in using -ArgumentList

$v1 = "123"$v2 = "asdf"$sb = {    param    (        $v1,        $v2    )    Write-Host "Values are: $v1, $v2"}$job = Start-Job -ScriptBlock $sb -ArgumentList $v1, $v2$job | Wait-Job | Receive-Job$job | Remove-Job