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 }
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 .
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With