1

A script fills several variables with various numbers and names with numbers (strings).

$mPS01
$mPS02
$mPS03
$mPS04
$mPS05

$sName_01
$sName_02
$sName_03
$sName_04
$sName_05

The command

Write-Host 'Var mPS01:' $mPS01 / $sName_01

perfectly outputs the content of this variable pair.

Question: How can those variables be displayed using a for-loop? (The number of numbered variables is known.)

Below is the code I started with, but I cannot get it to output the contents of the variables.

for($i = 1; $i -lt 6; $i++) { write-Host mPS0$i":"  $mPS0$i / $sName_0$i }

The output is numbered according to the value of $i instead of the variables corresponding contents.

mPS01: 1 / 1
mPS02: 2 / 2
mPS03: 3 / 3
mPS04: 4 / 4
mPS05: 5 / 5

I'd think there is some trick for proper formatting to achieve the desired output of the content, but I could not find a solution.

5
  • 2
    It might be better to explain what you actually want to do ... the bigger picture ... most of the times we do not use indexed variables. A better option would be to use arrays for example. And that would be easier to output in a loop as well. Commented Jul 30, 2022 at 6:53
  • 2
    There is a concept for numbered/indexed variables, it is called Arrays. Don't use numbered variables, use arrays! Commented Jul 30, 2022 at 7:18
  • 1
    If you tell us more about your problem, you might even want to use an array of custom objects. Commented Jul 30, 2022 at 7:23
  • In principle I agree, but in this case the values in the variables change as the script goes along. It would require more code working with an array. The accepted answer is exactly what I was looking for (and didn't find searching). Commented Jul 30, 2022 at 10:19
  • 1
    What you're looking for is variable indirection, where you refer to a variable indirectly, via its name stored in a different variable or provided by an expression. PowerShell enables this via the Get-Variable and Set-Variable cmdlets, but note that there are usually better alternatives. See the linked duplicate for details. Commented Jul 30, 2022 at 11:34

1 Answer 1

3

You can use the Get-Variable cmdlet to get the value.

$name1 = 'data1'
$name2 = 'data2'
$name3 = 'data3'
$name4 = 'data4'
$name5 = 'data5'

for($i = 1; $i -lt 6; $i++)
{
    $varName = "name$i"
    $value = (Get-Variable -Name $varName).Value
    Write-Host "$varName : $value"
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.