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

I want to use background jobs in Powershell.

How do I make the variables evaluated at the time the ScriptBlock is defined?

$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 am getting printable blank values ​​for $ v1 and $ v2. How can I evaluate them in the (passed in) scriptblock and thus in the background job?

+11


source to share


4 answers


One way is to use the [scriptblock] :: create method to create a script block from an expandable 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 InitializationScript:



$Init_Script = {
$v1 = "123"
$v2 = "asdf"
}

$sb = {
    Write-Host "Values are: $v1, $v2"
}

$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb 

      

The 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

      

+25


source


The simplest solution (requiring V3 or higher) looks like this:

$v1 = "123"
$v2 = "asdf"

$sb = {
     Write-Host "Values are: $using:v1, $using:v2"
}

$job = Start-Job -ScriptBlock $sb

      



You might think of $ using acting like an explicit param () block and passing in -ArgumentList, only PowerShell will automatically handle that for you.

+17


source


Declare the values ​​as parameters in the script block, then pass them 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

      

+2


source


I'm not on a computer to test, but this should work:

$sb = {
    param($p1,$p2)
    Write-Host "Values are: $p1, $p2"
}

$job = Start-Job -ScriptBlock $sb -ArgumentList $v1,$v2

      

I will double check this when I work.

+2


source







All Articles