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"?
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 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.
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar. length-1.
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.
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:
$array | select -First N
$array | select -Last N
$array | select -Skip N
$array | select -SkipLast N
$array | select -Skip N -First M
$array | select -Skip N -Last M
$array | select -Distinct
$array | select -Index (0,2,4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With