Home > Net >  Array of reference to var in powershell
Array of reference to var in powershell

Time:09-21

Ok I guess this question has already been answered somewhere but I do not find it. So here is my few lines of codes

$a = 0
$b = 0
$c = 0

$array = @($a, $b, $c)

foreach ($var in $array) {
    $var = 3
}
Write-Host "$a : $b : $c" 

What I try to do is loop into $array and modify a, b and c variables to get 3 : 3 : 3 ... I find something about [ref] but I am not sure I understood how to use it.

CodePudding user response:

You'll need to wrap the values in objects of a reference type (eg. a PSObject) and then assign to a property on said object:

$a = [pscustomobject]@{ Value = 0 }
$b = [pscustomobject]@{ Value = 0 }
$c = [pscustomobject]@{ Value = 0 }

$array = @($a, $b, $c)

foreach ($var in $array) {
    $var.Value = 3
}
Write-Host "$($a.Value) : $($b.Value) : $($c.Value)"

Since $a and $array[0] now both contain a reference to the same object, updates to properties on either will be reflected when accessed through the other

CodePudding user response:

As you mentioned you can use the [ref] keyword, it will create an object with a "Value" property and that's what you have to manipulate to set the original variables.

$a = 1
$b = 2
$c = 3

$array = @(
    ([ref] $a),
    ([ref] $b),
    ([ref] $c)
)

foreach ($item in $array)
{
    $item.Value = 3
}

Write-Host "a: $a, b: $b, c: $c" # a: 3, b: 3, c: 3
  • Related