3

我有 Powershell 工作。

$cmd = {
  param($a, $b)
  $a++
  $b++
}

$a = 1
$b = 2

Start-Job -ScriptBlock $cmd -ArgumentList $a, $b

如何通过参考$a$b在工作完成后更新它们?或者如何通过引用运行空间来传递变量?

4

2 回答 2

3

我刚刚写的简单示例(不要介意凌乱的代码)

# Test scriptblock
$Scriptblock = {
param([ref]$a,[ref]$b)
$a.Value = $a.Value + 1
$b.Value = $b.Value + 1
}

$testValue1 = 20 # set initial value
$testValue2 = 30 # set initial value

# Create the runspace
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.ApartmentState = [System.Threading.ApartmentState]::STA
$Runspace.Open()
# create the PS session and assign the runspace
$PS = [powershell]::Create()
$PS.Runspace = $Runspace

# add the scriptblock and add the argument as reference variables
$PS.AddScript($Scriptblock)
$PS.AddArgument([ref]$testValue1)
$PS.AddArgument([ref]$testValue2)

# Invoke the scriptblock
$PS.BeginInvoke()

运行此之后,测试值会更新,因为它们是由 ref 传递的。

于 2019-01-08T10:38:25.327 回答
3

正如@bluuf指出的那样,在 PowerShell 中通过引用传递参数总是很尴尬,而且可能无论如何都不适用于 PowerShell 作业。

我可能会做这样的事情:

$cmd = {
    Param($x, $y)
    $x+1
    $y+1
}

$a = 1
$b = 2

$a, $b = Start-Job -ScriptBlock $cmd -ArgumentList $a, $b |
         Wait-Job |
         Receive-Job

上面的代码将变量$a和传递$b给脚本块,并在收到作业输出后将修改后的值分配回变量。

于 2019-01-08T11:31:49.510 回答