Today we continue our series that answers common questions, or questions that have been asked about/of PowerShell. Create multiple variables using an array operator. What we intend to provide is one of the many, many ways you can accomplish these same tasks within PowerShell.
All of the solutions are ours and demonstrate the author’s skill and ability level at the time of writing. That is to say, we might not always write the best PowerShell code. However, if you know of a better way we welcome that input.
I have a series of variables that I need to assign the same value to. Is there an easier way to do it than one variable per line?
With PowerShell anything is possible. This can be completed for as many variables as you need to create. For instance, now your code looks like this:
$variable1=0 $variable2=0 $variable3=0
That is an acceptable way to do it if you are starting out and have not read this post yet. Let’s say instead of three variables we have 100. Can this stay on one line? Let’s break down the command to show you.
1..100 |
We start with creating an array and using the array operator (..
). In the above example we are saying “Everything from the number one (1
) to the number one hundred (100
).” We then pipe (|
) this information into the next section of this line.
ForEach-Object -Process { }
To continue with create variables using an array operator. The ForEach-Object
says that for each of the 1 through 100, so each one, two, three and so on, -Process
the following command block inside { }
New-Variable -Name "number$_" -Value 0
This command does all the work for us in creating the variable assigning the name, and value. We use the New-Variable
command with -Name
using the inline variable $_
to assign whichever number the ForEach-Object
is currently -Processing
, and to add the -Value 0
to the variable.
1..100 | ForEach-Object -Process {New-Variable -Name "variable$_" -Value 0}
This creates variables with the name $variable1
through $variable100
and assigns each variable the same -Value
, 0
.
Other Posts: