5

#PSTip Swapping the value of two variables

In most programming languages the conventional way to swap the value of two variable is to use a third variable.

PS> $a=1
PS> $b=2

PS> $temp = $a
PS> $a = $b
PS> $b = $temp

PS> "`$a=$a,`$b=$b"
$a=2,$b=1

In Windows PowerShell it is much easier. We can use multiple assignments to perform the same operation in less code and without a third variable.

PS> $a=1
PS> $b=2
PS> $a,$b = $b,$a
PS> "`$a=$a,`$b=$b"
$a=2,$b=1

You can also swap multiple variables. In the following example, $a will swap its value with $c, $b will swap its value with $d, and so on and so forth.

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

PS> $a,$b,$d,$c = $c,$d,$a,$b
PS> "`$a=$a,`$b=$b,`$c=$c,`$d=$d"
$a=3,$b=4,$c=2,$d=1
Filed in: Columns, Tips and Tricks Tags: , ,

2 Pingbacks/Trackbacks

5 Responses to "#PSTip Swapping the value of two variables"

  1. DVS says:

    This is too radical. Which way is faster and easier on memory?

    • PowerShellMag says:

      I haven’t tested performance but even if the conventional way is faster, I would sacrifice it for the convenience of the short way.

  2. Sergey Nazarov says:

    I like it

Leave a Reply

Submit Comment

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