What you're trying ⚠️
You might get the variables using the Get-Variable
cmdlet. By default the Get-Variable
(and the counterpart Set-Variable
) will include all known variables including other variables you created (e.g. $b1 = "valueB1"
), automatic variables (e.g. $args
) and everything that is inherited from a parent scope.
Therefore you need to be very careful with these cmdlets as you might easialy retrieve or overwrite the wrong variable.
$a1 = "value1"
$a2 = "value2"
$a3 = "value3"
$a4 = "value4"
$a5 = "value5"
$a = 1
DO {
"Starting Loop `$a$a"
Get-Variable -ValueOnly "a$a"
Set-Variable "a$a" "NewValue$a"
Get-Variable -ValueOnly "a$a"
$a++
} Until ($a -gt 5)
But as already suggested, Don't use the -Variable cmdlets for dynamic variable names!.
Instead
Create a new custom list of variables using a hash table and read and write your values in there:
$a = @{} # create a hash table
1..5 |% { $a[$_] = "value$_" } # count from 1 to 5 ($_ is the current item)
$a[3] # display the $a[3]
value3