Tuesday, February 17, 2009

Swapping variables with PowerShell

I’ve often had cases with programming where I want to swap the contents of two variables. For example, suppose I have two variables $a, and $b, and what we want is to have $a contain the value of $b and $b contain the value of $a.

As an old fashioned programmer, I’d do it this way:

# Assign some values
$a = 1
$b = 2
# now switch
$temp = $a
$a = $b
$b = $temp

Now that works, but it requires the use of a third variable ($temp). If $a and/or $b were large arrays (e.g. all the file objects on a system for example) this would waste a lot of RAM and cause a GC collection.

As it turns out, with PowerShell, there’s another way:

# Assign some values
$a = 1
$b = 2
# now switch
$a,$b = $b, $a

In this case, PowerShell treats the two sides of the “=” as arrays and does the necessary transposition of values.

Thanks to Tobias Weltner for pointing this out.

Technorati Tags: ,,