2
PS > $Index = 1
PS > $Variable1 = "Var1"
PS > $Variable = "Variable$Index"
PS > $Variable
Variable1

Is there any way to have $Variable becoming the value of another variable ($Variable1) by using both string and yet another variable ($Index) to target it, something like the above?

  • 2
    You can play around with (get-variable "Variable$($Index)").Value – Lieven Keersmaekers Feb 17 at 7:43
  • Thanks, this is exactly what I needed! If you leave it as an answer I'll gladly mark it. – Morten Feb 17 at 9:45
  • done with a disclaimer ;) – Lieven Keersmaekers Feb 17 at 9:58
2

You might want to explain your use case further because dynamically creating and using variables might not be the best solution.

That said, you can use (get-variable "Variable$($Index)").Value to start playing around and see how far it takes you.

| improve this answer | |
  • 1
    Yes, It would be useful to know more about the intended use of the desired technique. It almost seems as though the OP wants to something that is best accomplished by creating an array, and the referencing the array using the index as a selector. But only the OP can say whether that is the real intent. – Walter Mitty Feb 17 at 11:27
2

Depending on what you are really trying to accomplish, you might find it useful to learn how arrays work. Consider the following example:

$array = @("Var0", "Var1", "Var2")
$index = 1
$array[$Index]

The first step creates an array with three elements, and stores it in a variable. Note the inclusion of the entry for zero, before the entry for 1.

The second step stores the value 1 in a variable.

The third step uses the variable with value 1 as a selector to choose the right element in the array. Note that if Index had been zero, it would have picked the first element of the array.

This is a very common technique in powershell, but it may or may not be relevant to your use case.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.