Search code examples
powershell

Loop through variables not through an Array


I need loop through all the variables. But it doesn't work.

$var0='a'
$var1='b'
$var2='c'

$i=0; While ($i -lt 3) { 
$var[$i]
$i++}

enter image description here Most popular is

$var=('a','b','c')
$i=0; While ($i -lt 3) {
$var[$i]
$i++}

and it works.

But I need loop variables, was shown in the first block


Solution

  • You can do this:

    $var0='a'
    $var1='b'
    $var2='c'
    
    $ThisVar = 'var1'
    Get-Variable -Name $ThisVar -ValueOnly
    

    Which in turn means you can do this:

    $var0='a'
    $var1='b'
    $var2='c'
    
    $i=0; While ($i -lt 3) {
    $ThisVar = "var$i"
    Get-Variable -Name $ThisVar -ValueOnly
    $i++}
    

    And this:

    $var0='a'
    $var1='b'
    $var2='c'
    
    $i=0; While ($i -lt 3) {
    Get-Variable -Name "var$i" -ValueOnly
    $i++}