Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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"?

like image 596
Dominic Brunetti Avatar asked Dec 08 '17 00:12

Dominic Brunetti


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].

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.

How do you access array elements in PowerShell?

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar. length-1.

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


1 Answers

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)
like image 200
Reza Aghaei Avatar answered Oct 03 '22 14:10

Reza Aghaei