Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 887
mhopkins321 Avatar asked Oct 22 '12 16:10

mhopkins321


People also ask

How do you create a new variable in PowerShell?

To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .

What is the $_ variable in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

How do I assign multiple values to a variable in PowerShell?

Assigning multiple variables In PowerShell, you can assign values to multiple variables using a single command. The first element of the assignment value is assigned to the first variable, the second element is assigned to the second variable, the third element to the third variable.


1 Answers

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 } 
like image 180
Roman Kuzmin Avatar answered Sep 22 '22 18:09

Roman Kuzmin