Take the last N elements of an array instead of first elements in PowerShell

12,287

To take last N elements of an array, you can use either of the following options:

  • $array | select -Last n
  • $array[-n..-1] (← '..' is the Range Operator)

Example

$domain = "my.new.domain.com"
$domain.Split('.') | select -Last 2

Will result in:

domain
com

Note

Using the select cmdlet, you can do some jobs that you usually do using LINQ in .NET, for example:

  • Take first N elements: $array | select -First N
  • Take last N elements: $array | select -Last N
  • Skip first N elements: $array | select -Skip N
  • Skip last N elements: $array | select -SkipLast N
  • Skip and take from first: $array | select -Skip N -First M
  • Skip and take from last: $array | select -Skip N -Last M
  • Select distinct elements: $array | select -Distinct
  • select elements at index: $array | select -Index (0,2,4)
Share:
12,287
Dominic Brunetti
Author by

Dominic Brunetti

Updated on June 09, 2022

Comments

  • Dominic Brunetti
    Dominic Brunetti almost 2 years

    Quick question. I have the following:

    $domain = "my.new.domain.com"
    $domain.Split('.')[0,1]
    

    ...which returns the value:

    my
    new
    

    That's great except I need the LAST TWO (domain.com) and am unsure how to do that. Unfortunately the number of splits is variable (e.g. test.my.new.domain.com). How does one say "go to the end and count X splits backwards"?