powershellpass-by-referencepowershell-jobs

How to pass variable by reference to Powershell job or runspace?


I have Powershell job.

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

$a = 1
$b = 2

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

How to pass $a and $b by a reference so when the job is done they will be updated? Alternatively how to pass variables by reference to runspaces?


Solution

  • Simple sample I just wrote (don't mind the messy code)

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

    After running this the for the testvalues are updated since they are passed by ref.