#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&gt; &quot;<code>$a=$a,</code>$b=$b&quot;

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&gt; $a=1
PS&gt; $b=2
PS&gt; $a,$b = $b,$a
PS&gt; &quot;<code>$a=$a,</code>$b=$b&quot;

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&gt; $a=1
PS&gt; $b=2
PS&gt; $c=3
PS&gt; $d=4

PS&gt; $a,$b,$d,$c = $c,$d,$a,$b
PS&gt; &quot;<code>$a=$a,</code>$b=$b,<code>$c=$c,</code>$d=$d&quot;
Filed in: Columns, Tips and Tricks Tags: , ,

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

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