Хвост массива в powershell

Перебираем, сортируем, фильтруем и делаем с массивами всякое.

Хвост массива в powershell

Изучите основы Python на практике. Бесплатно ➞

Мини-курс для новичков и для опытных кодеров. 4 крутых проекта в портфолио, живое общение со спикером. Кликните и узнайте, чему можно научиться на курсе.

To answer the question contained in your post’s title:

What is the equivalent of str.Substring in PowerShell?

PowerShell offers virtually unlimited access to all .NET APIs, so you’re free to call the System.String type’s .Substring() directly; e.g.:

# -> 'file.cpp'
"C:/Users/xxx/Projects/file.cpp".Substring(22)

I just need everything after the last “/”.

# -> 'file.cpp'
"C:/Users/xxx/Projects/file.cpp".Split('/')[-1]

PowerShell itself offers the -split operator, whose RHS, the split criterion, is interpreted as a regex by default (with / that doesn’t make a difference):

# -> 'file.cpp'
("C:/Users/xxx/Projects/file.cpp" -split '/')[-1]

See this answer for why using -split over .Split() is generally preferable, considering the tradeoffs involved.


# -> 'file.cpp'
"C:/Users/xxx/Projects/file.cpp" -replace '^.*/'

For a comprehensive but concise summary of -replace, see this answer.


Finally, only with separators / and \, you can use the Split-Path cmdlet’s -Leaf parameter, taking advantage of the fact that PowerShell recognizes \ and / interchangeably as path (directory) separators:

# -> 'file.cpp'
Split-Path -Leaf "C:/Users/xxx/Projects/file.cpp"


Often you may want to slice an array in PowerShell to extract only specific elements.

Method 1: Extract Specific Range of Elements from Array

[3..8]

This particular example will extract each of the elements in index positions 3 through 8 in the array named my_array.

Note: The first element in the array has an index value of 0.

Method 2: Extract First N Elements from Array

 | -First 7

This particular example will extract the first 7 elements in the array named my_array.

:/>  Как долго устанавливается windows 7

Method 3: Extract Last N Elements from Array

 | -Last 7

This particular example will extract the last 7 elements in the array named my_array.

Example 1: Extract Specific Range of Elements from Array in PowerShell

 = 4, 15, 20, 22, 30, 45, 50, 51, 23, 29
[3..8]

PowerShell slice specific range of elements in array

Notice that this returns only the elements in index positions 3 through 8 from the array.

Example 2: Extract First N Elements from Array in PowerShell

 = 4, 15, 20, 22, 30, 45, 50, 51, 23, 29
 | -First 7

PowerShell slice first N elements in array

Notice that this returns only the first 7 elements from the array.

Example 3: Extract Last N Elements from Array in PowerShell

 = 4, 15, 20, 22, 30, 45, 50, 51, 23, 29
 | -Last 7

PowerShell slice last N elements from array

Notice that this returns only the last 7 elements from the array.

PowerShell: How to Compare Two Arrays
PowerShell: How to Get First Item in Array
PowerShell: How to Calculate the Average of an Array
PowerShell: How to Find Duplicate Values in Array

In powershell I can get the tail of an array by doing this:

$array = 1..10
$tail = $array[-($array.Length-1)..-1]

I am correctly getting the tail of the array, i.e.,

Is this the best I can do?
Is there a better looking alternative?

matilda chi's user avatar

Select-Object -Last is the easiest option in my opinion:

$array | Select-Object -Last 9 # last 9 elements from the array

You can also use -Skip:

$array | Select-Object -Skip 1 # skip the first element

However you should be aware that both alternatives, indexing as in your question and Select-Object will end up creating a new array and can add overhead to your code. If you need to perform this operation many times, the recommended approach is an ArraySegment<T>:

$array = 1..10
$segment = [System.ArraySegment[int]]::new($array)
$segment.Slice(1) # from index 1 till the end
$segment.Slice(1, $segment.Count - 3) # 7 elements starting from index 1

The .Slice method outputs an ArraySegment<T> making it very efficient, then if you need to materialize that slice you can call its .ToArray() method.

:/>  Тест скорости с power shell

Santiago Squarzon's user avatar

You can use $null to capture the first element on assignment, then store the rest in $tail like so:

$null, $tail = $array

Mathias R. Jessen's user avatar

Mathias R. JessenMathias R. Jessen

12 gold badges164 silver badges221 bronze badges

Presuming that the 1 in $array.Length-1 should be dynamic like:

$Skip = 1
$array[-($array.Length-$Skip)..-1]

You could also change this to:

$array[$Skip..($array.Length-1)]

And knowing that PowerShell isn’t strict by default (meaning unless you do something like Set-StrictMode -Version Latest), you might even do something like this:

$Array[$Skip..9999]

iRon's user avatar

10 gold badges56 silver badges89 bronze badges