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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like