Arrays in PowerShell

Published 23 October 07 08:39 AM | john 

While I'm waiting for some files to copy around I thought I'd record my recent PowerShell learnin'.

Somtimes a command, like Get-ChildItem can return either an array of results or just a single one.  You can use the @ symbol to cast the result into an array, so:

(gci -i *.txt).Count

Sometimes returns nothing, whereas:

@(gci -i *.txt).Count

Always returns the count of *.txt files.

Second thing.  The .. is the syntax for ranges.  So 1..10 is expanded into an array of the numbers 1 thru 10.   Turns out you can also use arrays as indexes!  Each item in the index array is used to index an item in the data array, thus returning a new array.

There's an example in the help that is confusing at first sight:

$a[0..-2]

Returns the first, last and second to last elements in the array in that order.  Why? Because the range is expanded into a list, equivalent to:

$a[-2,-1,0]

Make sense? 

If you write blogs with code in and you are using LiveWriter grab the Insert Code for Windows Live Writer plug-in.  It's got some flaws, but it's a huge time saver.

Filed under: ,

Comments

No Comments
Anonymous comments are disabled