且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PowerShell的 - 如何美元的启动工作一个脚本块p $ P-评估变量

更新时间:2023-01-08 19:10:50

一种方法是使用[脚本块] :: Create方法使用的局部变量的expanadable字符串创建脚本块:

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

的另一种方法是设置在InitializationScript变量:

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 

第三个选项是使用-ArgumentList参数:

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