Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array index from first to second last in PowerShell

How can I get the array element range of first to second last?

For example,

$array = 1,2,3,4,5
$array[0] - will give me the first (1)
$array[-2] - will give me the second last (4)
$array[0..2] - will give me first to third (1,2,3)
$array[0..-2] - I'm expecting to get first to second last (1,2,3,4) but I get 1,5,4 ???

I know I can do long hand and go for($x=0;$x -lt $array.count;$x++), but I was looking for the square bracket shortcut.

like image 396
RM1358 Avatar asked May 01 '14 00:05

RM1358


People also ask

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].

Do PowerShell arrays start at 0 or 1?

A common programming error is created because arrays start at index 0.

How do I sort an array in PowerShell?

There are actually two ways to do this. The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System. Array .

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.


3 Answers

You just need to calculate the end index, like so:

$array[0..($array.length - 2)]

Do remember to check that you actually have more than two entries in your array first, otherwise you'll find yourself getting duplicates in the result.

An example of such a duplicate would be:

@(1)[0..-1]

Which, from an array of a single 1 gives the following output

1 
1
like image 93
Robert Westerlund Avatar answered Nov 02 '22 20:11

Robert Westerlund


As mentioned earlier the best solution here: $array[0..($array.length - 2)]

The problem you met with $array[0..-2] can be explained with the nature of "0..-2" expression and the range operator ".." in PowerShell. If you try to evaluate just this part "0..-2" in PowerShell you will see that result will be an array of numbers from 0 to -2.

>> 0..-2
0
-1
-2

And when you're trying to do $array[0..-2] in PowerShell it's the same as if you would do $array[0,-1,-2]. That's why you get results as 1, 5, 4 instead of 1, 2, 3, 4.

It could be kind of counterintuitive at first especially if you have some Python or Ruby background, but you need to take it into account when using PowerShell.

like image 25
FamousSnake Avatar answered Nov 02 '22 20:11

FamousSnake


There might be a situation where you are processing a list, but you don't know the length. Select-object has a -skiplast parameter.

(1,2,3,4,5 | select -skiplast 2)

1
2
3
like image 25
js2010 Avatar answered Nov 02 '22 21:11

js2010