Increment Variable Name Using Another Variable

Increment Variable Name Using Another Variable

I am creating many variables that end with an incrementing number,

$var0 = "foo"
$var1 = "bar"
$var2 = "ack"
$var3 = "influenza"      # ran out of fillers

I want to check each of these variables for the one containing "ack". My thinking is to use a for, increment $i, and use $i at the end of each variable name.

for($i=0;$i -le 3;$i++) {
    if((Get-Variable -Name "var$i" -ValueOnly) -eq "ack") {
        "result at var$i"
    }
    else {
        $i
    }
}

Is there a more elegant way than Get-Variable to use $i as part of a variable name? Or is the point to use an array in this scenario?

3

1 Answer

The solution was to use an array instead of using multiple variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.