PowerShell syntax help: how do you use a variable created within the script itself?

Status
Not open for further replies.

RojBlake

Ars Legatus Legionis
48,129
Subscriptor
Let's say we have something like this, which creates five new variables called var1, var2, var3..., etc.
Code:
for($i = 1; $i -le 5; $i ++)
   {
   New-Variable -Name var$i -Value "foo"
   }
If I wanted to then list/refer back to those variables without explicitly calling them (because the script isn't going to know what they are at runtime), is there way to do that? Thus far I haven't been able to figure it out and my google-fu is failing me.

I thought it would be something like...
Code:
for($i = 1; $i -le 5; $i ++)
   {
   $var$i
   }
...but PowerShell responds to $var$i with the red text of shame and no other syntactic variant I've tried works.

As a workaround, I'm doing something like...
Code:
$list = Get-Variable | ?{$_.Name -like "var*"}
...and then futzing about iterating through $list to find what I'm looking for. But that's both risky (what if there's already a variable called $var(something)?) and cumbersome.

Is there a better way?
 
Status
Not open for further replies.