1

I have this code:

$a1 = "value1"
$a2 = "value2"
$a3 = "value3"
$a4 = "value4"
$a5 = "value5"

DO {
    "Starting Loop $a1"
    $a1
    $a1++
    "Now `$a is $a1"
} Until ($a1 -eq "value5")

i try to make the loop stop once it reach value5. The question is how i can go pass through all the variables, so if $a1 is not value5 it go to $a2. Thanks.

6
  • @jsotola what should the title be? "Stop Do Until loop once it reach certain variable"? Commented Dec 11, 2020 at 2:39
  • okay, i using your title suggestion lol Commented Dec 11, 2020 at 2:48
  • Does this answer your question? Dynamically create variables in PowerShell Commented Dec 11, 2020 at 2:52
  • 4
    @Griz - generally speaking, one otta not use a series of $Var names. instead, store them in a collection of some sort. that makes working thru them MUCH easier ... just use foreach ($Item in $Collection) ... [grin] Commented Dec 11, 2020 at 2:56
  • 1
    @Griz, what Lee_Dailey is trying to say, is that this is an odd request. Most people do not use variables in this way. Most people would use something like an array. So you would have a single variable, which contains multiple items. And then you can loop though the array. Generally when odd questions like this come up, it's because you're likely trying to solve a problem with the wrong tools. Commented Dec 11, 2020 at 6:39

1 Answer 1

2

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

1 Comment

Please accept the answer (or tell me what is missing), so that I can use it for other duplicated questions as e.g.: Use Dynamically Created Variable Name Within a Variable 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.