mhopkins321
mhopkins321

Reputation: 3073

Dynamically create variables in PowerShell

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
}

Upvotes: 38

Views: 101635

Answers (1)

Roman Kuzmin
Roman Kuzmin

Reputation: 42035

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
}

Upvotes: 59

Related Questions