Reputation: 51
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.
Upvotes: 0
Views: 104
Reputation: 110
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
You could also use the function Get-Variable
to get variables:
$varA = Get-Variable -Name a
This way you can get more information about the variable like the name.
And if your variables have some kind of prefix you could get them all using a wildcard.
$variables = Get-Variable -Name my*
And you would get all variables that start with "my".
Upvotes: 1
Reputation: 174485
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
Upvotes: 2