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.

Olaf
  • 4,690
  • 2
  • 15
  • 23
snahl
  • 497
  • 2
  • 10
  • 25
  • 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. – Olaf Jul 30 '22 at 06:53
  • 2
    There is a concept for numbered/indexed variables, it is called [Arrays](https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays). Don't use numbered variables, use arrays! – stackprotector Jul 30 '22 at 07:18
  • 1
    If you tell us more about your problem, you might even want to use an array of [custom objects](https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject). – stackprotector Jul 30 '22 at 07: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). – snahl Jul 30 '22 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`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable) and [`Set-Variable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-variable) cmdlets, but note that there are usually better alternatives. See [the linked duplicate](https://stackoverflow.com/q/68213804/45375) for details. – mklement0 Jul 30 '22 at 11:34

1 Answers1

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"
}
Lukas
  • 138
  • 6