0

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.

5
  • What is $a, $b and $c? Commented Sep 21, 2022 at 14:57
  • I edited my question so it is more understandable Commented Sep 21, 2022 at 15:01
  • You can't do that. Information about variables $a, $b and $c are not actually contained in the array Commented Sep 21, 2022 at 15:05
  • I do understand that but is there anyway that instead of storing a b and c value in the array I can store pointers or reference or something to access the variable ? @Mathias R. Jessen Commented Sep 21, 2022 at 15:09
  • I think this is where you heading to: How do I automaticaly create and use variable names? Commented Sep 21, 2022 at 15:54

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.