40

How do I create a new variable each time a loop runs?

Something along the lines of

for ($i=1; $i -le 5; $i++)
{
    $"var + $i" = $i
    write-host $"var + $i
}

1 Answer 1

61

Use New-Variable and Get-Variable (mind available options including scopes). E.g.

for ($i=1; $i -le 5; $i++)
{
    New-Variable -Name "var$i" -Value $i
    Get-Variable -Name "var$i" -ValueOnly
}
Sign up to request clarification or add additional context in comments.

6 Comments

perfectly valid answer. I would add that anytime that I need to do something like this, I prefer to use a hash table.
I also prefer hashtables. Still, there are some (rare) cases where only these cmdlets help.
An example is in a psake block like the properties block where you need to do something REALLY dynamic.
Can you give an example of how you would answer the original question using a hashtable @EBGreen? I'm not seeing how hashtables would help for this scenario? Or can you show what alternative scenario you are referring to?
@YorSubs here is the example: $data = @{}; for ($i=1; $i -le 5; $i++) { $data["var$i"] = $i; Write-Host $data["var$i"] }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.