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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…