代码之家  ›  专栏  ›  技术社区  ›  Yoda ESG

如何通过引用将变量传递给PowerShell作业或运行空间?

  •  1
  • Yoda ESG  · 技术社区  · 7 年前

    我有PowerShell作业。

    $cmd = {
      param($a, $b)
      $a++
      $b++
    }
    
    $a = 1
    $b = 2
    
    Start-Job -ScriptBlock $cmd -ArgumentList $a, $b
    

    如何通过 $a $b 通过一个参考,那么当工作完成时,他们将被更新?或者,如何通过引用运行空间来传递变量?

    2 回复  |  直到 7 年前
        1
  •  1
  •   bluuf    7 年前

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

    # 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()
    

    运行此命令后,将更新for the testvalues,因为它们是由ref传递的。

        2
  •  2
  •   Ansgar Wiechers    7 年前

    在PowerShell中,通过引用传递参数总是很难,而且可能无论如何都不能用于PowerShell作业,因为 @bluuf 指出。

    我可能会这样做:

    $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 到脚本块,并在接收到作业输出后将修改后的值分配回变量。

    推荐文章