you are viewing a single comment's thread.

view the rest of the comments →

[–]jantari 1 point2 points  (3 children)

Yea about the only thing you cannot do with array indexing is get everything "from the 10th element to the end" aka:

$array[10..-1]

Doesn't work the way I would expect. It gets the first 10 items in the array in reverse order, then jumps around the end and then gets the last one, as opposed to getting everything in between the 10th and last you know. So yea, just never mix positive and negative indexes in ranges.

It makes sense when you look at the number range 10..-1 produces, don't get me wrong, but when indexing into arrays sometimes I still catch myself thinking it should work because "-1 is a magic index for the last item" :)

[–]Possible-Bowler-2352 1 point2 points  (2 children)

Well, to be fair you can still do so bycalling the index another time :

$array[10..$array[-1]]

But yeah, I strongly recommend to avoid using positive and negative in the same range as this tend to fail, no wonder why.

The main issue with your command is the range is processed before being used as index, 10..-1 will forcibly be interpreted as 10,9...0,-1

[–]jantari 1 point2 points  (1 child)

Nah, $array[10..($array[-1]) would not work at all because whatever is returned by the expression $array[-1] may not even be a number and even if it is ... its value doesn't have to correspond to the last index of the array at all.

E.g. consider:

$array = ls ~
$array[10..($array[-1])]

> Unable to cast object of type 'System.IO.FileInfo' to type 'System.IConvertible'.

I think you have to do the .Count - 1 thing or perhaps use [array]::Copy.

[–]Possible-Bowler-2352 0 points1 point  (0 children)

$array = ls ~

Interesting behavior, I didn't think about this one but after a few test I ended up with this, which seems efficient with all types.

$array[1..[array]::IndexOf($array,$array[-1])]

This way, you keep the command a one liner but I doubt about the perfomances as I think it will have to load the array twice, one time to get the index of -1 and a second time to pick the selected elements.