PowerShell Tip: How to “shift” arrays…

PowerShell Team

It’s fairly common in scripts to extract the first element out of an array then “shift” the remaining elements. Perl has a special shift operator for doing this as do many of the UNIX shells. PowerShell, however, doesn’t have a shift operator built-in. So how do we shift arrays in PowerShell? Well – we could do it the brute force way and simply copy all of the elements after the first one but that sounds like too much work. A way to make it a bit easier is to use the range operator (‘..’) and array slices as shown:

$first = $oldArray[0]


This behavior can be misleading, if you get down to 1 element left in the array and do `$oldArray = $oldArray[1 .. ($oldArray.count-1)]` it will not remove the last element

$oldArray = $oldArray[1 .. ($oldArray.count-1)]

But that’s still too much typing. In practice, PowerShell’s multiple assignment feature is the most effective way to handle this kind of thing. Consider the following array:

PS (1) > $a = 1,2,3,4,5

We can use multiple assignment to split this array into $first and $rest simply by doing:

PS (2) > $first, $rest = $a

The first element from the array is placed into $first, the remaining elements are copies into $rest

PS (3) > $first


PS (4) > $rest






This behavior is outdated, $rest will no longer be an array if you do $null,$rest=$rest. It will be an System.Int32

If we don’t care about the first element, then we can use $null instead of $first and the value will simply be discarded.

PS (5) > $null, $rest = $rest

PS (6) > $rest




PS (7) >

This is actually a pretty handy approach to solving a variety of list restructuring problems. For example, say we have a list that looks like:

PS (7) > $list = “one”,1,”two”,2,”three”,3

The form of this list is simply a name followed by a value:

PS (8) > $list







Now I want to “fold” that list into a hashtable as a set of key/value pairs. Here’s a one-liner that will do this:

PS (9) > $hash = @{} ; while ($list) { $key, $value, $list = $list; $hash[$key]=$value }

The first two elements of the list go into $key and $value. The remaining elements are assigned back to $list. This loops until $list is empty. The resulting hash table looks like:

PS (10) > $hash

Name Value

—- —–

two 2

three 3

one 1


Bruce Payette [MSFT]

Windows PowerShell Tech Lead

Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell

Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Windows PowerShell in Action (book): http://manning.com/powershell


Discussion is closed.

Feedback usabilla icon