PowerShell: How to Remove First Element from an Array


Often you may want to remove only the first element from an array in PowerShell.

The easiest way to do so is by using the following syntax:

$new_array = $my_array[1..$my_array.length]

This particular example removes the first element from the array named $my_array and saves the results in a new array named $new_array.

Note that this syntax works by using $my_array[ ] to slice specific values from the array.

Within the brackets, we specify [1..$my_array.length] to extract all values ranging from the value in index position 1 to the last index position.

Since the first element in the array has an index position of 0, this effectively removes the first element from the array.

Example: How to Remove First Element from Array in PowerShell

Suppose that we create the following array in PowerShell named $my_array:

$my_array = 4, 15, 20, 22, 30, 45, 50

We can use the following syntax to remove the first element from the array and save the results in a new array named $new_array:

$new_array = $my_array[1..$my_array.length]

The following screenshot shows how to use this syntax in practice:

Notice that the first element of the array has been removed and the results have been saved in a new array named $new_array.

Note that you can use similar syntax to remove the first n elements from an array.

For example, you can use the following syntax to remove the first two elements from the array:

$new_array = $my_array[2..$my_array.length]

The following screenshot shows how to use this syntax in practice:

PowerShell remove first n elements from array

Notice that the first two elements of the array have been removed and the results have been saved in a new array named $new_array.

Feel free to replace 2 with any number you’d like to remove the first n elements from an array.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

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

Leave a Reply