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?
source to share
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
source to share
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.
source to share
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
source to share