1

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

10
  • 2
    What is it actually what you're trying to do? Most of the time it is not necessary to loop through a bunch of variables. If you insist you could enumerate the variables with getting the content of the drive variable: with a filter for the names you choose ... Commented Jun 29, 2024 at 10:05
  • 4
    Try (get-variable "var$i”).Value, although as others have said, looping through variables is often an indicator that there’s a better data structure to be using, like an array / hashtable… Commented Jun 29, 2024 at 11:30
  • 1
    Get-ChildItem -Path variable: | Where-Object -Property Name -Like -Value var* ... 🤷🏼‍♂️ ... but again ... what is it what you're actually trying to do? You're probably doing something wrong ... or at least way more cumbersome than necessary. Commented Jun 29, 2024 at 11:39
  • 1
    Cases like this is where a hashtable is just better, $variables = @{ var0 = 'a'; var1 = 'b'; ... } then $variables.GetEnumerator() | % { $varname = $_.Key; $varvalue = $_.Value ... } Commented Jun 29, 2024 at 14:55
  • 2
    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, such as hashtables. See the linked duplicates for details. Commented Jun 29, 2024 at 21:42

1 Answer 1

2

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++}
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thank you! As a result I did: (Get-Variable -Name $ThisVar).name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.