PowerShell: How to Reverse the Elements of an Array


Often you may want to reverse the order of elements in an array in PowerShell.

You can use the following syntax to do so:

$new_array = @([System.Collections.Stack]::new(@($my_array)))

This particular example creates a new array named $new_array that reverses the order of the elements in the array named $my_array.

Note that this syntax uses the System.Collections.Stack .NET class, which returns a last-in-first-out collection of objects by default.

This means that the last element in the array becomes the first element, the second to last element becomes the second element, and so on.

Note that we wrapped the entire expression with the @ symbol to force the output to be an array.

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

Example: How to Reverse the Elements of an Array in PowerShell

We can use the following syntax to create an array named $my_array that contains the values 1 through 10:

$my_array = 1..10

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

Now suppose that we would like to reverse the elements of this array.

We can use the following syntax to do so:

$new_array = @([System.Collections.Stack]::new(@($my_array)))

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

PowerShell reverse array

Notice that the new array named $new_array now contains the values 10 through 1 in descending order, which is the exact reverse order of the original array.

We can also confirm that this new object is indeed an array by using the following syntax:

$new_array -is [array]

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

This returns a value of True, which confirms that the new object named $new_array is indeed an array.

Note: You can find the complete documentation for the System.Collections.Stack .NET class here.

Related Tutorials

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

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array of Arrays
PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply