#PSTip Multiple variable assignments

In the previous tip I showed how we can use multiple assignments to swap the value of two or more variable values. In today’s tip we’ll see another cool use of multiple assignments. Consider the following variable assignment.

$a = 1
$b = 2
$c = 3
$d = 4

And with multiple assignments

PS> $a,$b,$c,$d = 1,2,3,4
PS> $a,$b,$c,$d
1
2
3
4

Big difference! Less lines of code and much more elegant. Each value of the collection on the right hand side is assigned to its corresponding variable on the left side.

We can also assign the value of an array/collection to a series of variables. Here’s an example that using the Range operator:

PS> $d,$e,$f,$g = 4..7
PS> $d,$e,$f,$g
4
5
6
7

# or with
PS> $one,$two,$three,$four = '1 2 3 4'.Split()
PS> $one,$two,$three,$four
1
2
3
4

One important thing to keep in mind is that if the collection of values is bigger than the number of variables, all remaining values will accumulate in the last variable. In the following example, variables $a, $b, and $c will contain their corresponding values (e.g 1, 2 and 3), but $d will contain multiple values: 4, 5, and 6.

PS> $a,$b,$c,$d = 1,2,3,4,5,6

PS> $d
4
5
6

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: