PowerShell: How to Remove Last Item from Array


You can use the following syntax in PowerShell to remove the last item from an array:

$my_array[0..($my_array.length-2)]

This particular example will remove the last item in the array named $my_array.

Note that we use brackets to select a specific range of items from the array.

The first item we select is in index position 0, which is the first item in the array.

The last item we select is equal to the length of the array minus 2, which is the second to last item in the array.

By using this syntax, we’re able to select all items in the array except for the last item.

The following example shows how to use this syntax in practice.

Example: How to Remove Last Item from Array in PowerShell

Suppose that we create an array in PowerShell named $my_array that contains 10 total values.

We can use the following syntax to create this array and then remove the last item from the array: 

$my_array = @(2, 4, 6, 3, 18, 14, 19, 22, 3, 40)
$my_array[0..($my_array.length-2)]

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

PowerShell remove last item from array

We can see that the last item from the array (the value 40) has been removed while all other items remain.

Note that you can also remove the last N items from an array by imply changing the the -2 in the code to a different number.

For example, we could use the following syntax to instead remove the last 3 items from the array:

$my_array = @(2, 4, 6, 3, 18, 14, 19, 22, 3, 40)
$my_array[0..($my_array.length-4)]

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

PowerShell remove last N items from array

We can see that the last 3 items have been removed from the array.

Feel free to replace -2 with any value that you’d like to remove a specific number of items from the end of the array.

Related Tutorials

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

PowerShell: How to Count Occurrences of Each Element in Array
PowerShell: How to Reverse the Elements of an Array
PowerShell: How to Calculate Sum of Values in Array

Leave a Reply