Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
Yoda Avatar asked Oct 21 '25 19:10

Yoda


1 Answers

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.

like image 63
bluuf Avatar answered Oct 23 '25 16:10

bluuf