2

#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
Filed in: Columns, Tips and Tricks Tags: , ,
  • DVS

    I’ll have to go through my old scripts and see where I can use this. Does the multiple variable assignments work in all versions of Powershell?

    Invoke-Expression “$((97..(97+25)|%{“`$$([char]$_)”}) -join ‘,’)=$((1..26) -join ‘,’)”

    • PowerShellMag

      Yes, since v1.

      $a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z=1..26

© 2014 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: