Search code examples
arrayspowershellindexingthisself-reference

Powershell $this variable does not work inside array indexing


I'm trying to emulate MATLAB's 'end' indexing keyword (such as A[5:end]) in Powershell but I don't want to type the array name (such as $array) to access $array.length for

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

as discussed in another Stackflow question. I tried $this

(0..7)[4..($this.Length-1)]

given ($this.Length-1) seems to be interpreted as -1 as the output shows

4
3
2
1
0
7

This makes me think $this is empty when used inside [] indexing an array. Is there a way for an array to refer to itself without explicitly repeating the variable name so I can call the methods of the array to derive the indices? This would be very handy for emulating logical indexing while taking advantage of method chaining (like a.b.c.d[4..end]).


Solution

  • PowerShell doesn't have any facility for referring to "the collection targeted by this index access operator", but if you want to skip the first N items of a collection/enumerable you can use Select -Skip:

    0..7 |Select -Skip 4