一种方法是使用 [scriptblock]::create 方法从使用局部变量的可扩展字符串创建脚本块:
$v1 = "123"
$v2 = "asdf"
$sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")
$job = Start-Job -ScriptBlock $sb
另一种方法是在 InitializationScript 中设置变量:
$Init_Script = {
$v1 = "123"
$v2 = "asdf"
}
$sb = {
Write-Host "Values are: $v1, $v2"
}
$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb
第三种选择是使用 -Argumentlist 参数:
$v1 = "123"
$v2 = "asdf"
$sb = {
Write-Host "Values are: $($args[0]), $($args[1])"
}
$job = Start-Job -ScriptBlock $sb -ArgumentList $v1,$v2