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

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: