PowerShell List Assignment

PowerShell and lists of data go together hand-in-hand. Any time you execute a cmdlet, function, or script, the output is a list of objects which is placed in the output stream for processing.

Assigning a list to a variable is not very interesting, either. You just assign it and it’s done. Like this, for instance:

$files=dir c:\temp

Nothing to see here, we do this every time we use PowerShell. Lists on the right-hand side of the assignment operator are boring.

You might have even seen a trick for swapping variables using a comma on the left-hand side like this:

$a,$b=$b,$a

That’s kind of cool, but it seems like a pretty specific kind of thing to do. Fortunately for us, lists on the left-hand side can do more that this.

As an example, consider this line:

$a,$b=1,2,3

If you look at $a, you’ll see that it got the 1, and $b got 2 and 3.

We can expand the example:

$a,$b,$c=1,2,3,4,5,6

Now, $a gets 1, $b gets 2, and $c gets 3,4,5 and 6.

The pattern should be clear. Each variable on the left gets a single object, until the last one which gets all remaining objects. If we have more variables than values, the “extra” variables are $null. If you specify the same variable more than once, it keeps the last corresponding value.

Why is this useful?

Well, if you want to work with a collection but treat the first item specially, now you have an easy way to do that.

$first,$rest = <however you get your collection>
<process $first>
<process $rest>

Probably not something you’ll do all the time, but it’s another trick in the bag.

Do you have any scenarios where this would be helpful? Let me know in the comments.

-Mike