PowerShell Script to Reverse Array Easily
Use
$reversed = $array[-1..-($array.Length)] or clone and use [array]::Reverse() method to reverse an array in PowerShell.Examples
Input[1, 2, 3]
Output[3, 2, 1]
Input['apple', 'banana', 'cherry']
Output['cherry', 'banana', 'apple']
Input[]
Output[]
How to Think About It
To reverse an array, think of flipping the order of elements so the last becomes first and the first becomes last. You can do this by creating a new array that picks elements starting from the end going to the start, or by using built-in methods that handle this flipping automatically.
Algorithm
1
Get the input array.2
Create a new array that contains elements from the original array starting from the last element to the first.3
Return or print the new reversed array.Code
powershell
$array = 1, 2, 3, 4, 5 $reversed = $array[-1..-($array.Length)] Write-Output $reversed
Output
5
4
3
2
1
Dry Run
Let's trace reversing the array [1, 2, 3] through the code
1
Original array
[1, 2, 3]
2
Create reversed array using negative indices
Indices used: -1..-3 which picks elements 3, 2, 1
3
Output reversed array
[3, 2, 1]
| Index | Element |
|---|---|
| -1 | 3 |
| -2 | 2 |
| -3 | 1 |
Why This Works
Step 1: Using negative indices
PowerShell allows using negative indices to count from the end of the array, so -1 is the last element.
Step 2: Range operator
The range -1..-($array.Length) creates a sequence from the last index to the first index.
Step 3: Creating reversed array
Selecting elements with this range reverses the order without modifying the original array.
Alternative Approaches
Using [array]::Reverse() method
powershell
$array = 1, 2, 3, 4, 5 $copy = $array.Clone() [array]::Reverse($copy) Write-Output $copy
This method reverses the array in place, so clone first to keep original unchanged.
Using a for loop to build reversed array
powershell
$array = 1, 2, 3, 4, 5 $reversed = @() for ($i = $array.Length - 1; $i -ge 0; $i--) { $reversed += $array[$i] } Write-Output $reversed
Manual approach, useful for learning but less efficient for large arrays.
Complexity: O(n) time, O(n) space
Time Complexity
Reversing requires visiting each element once, so time grows linearly with array size.
Space Complexity
Creating a reversed copy needs extra space proportional to the array size.
Which Approach is Fastest?
Using [array]::Reverse() in place is fastest and uses less memory but changes original array; slicing with negative indices is clean and safe but uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Negative indices slicing | O(n) | O(n) | Safe reversal without changing original |
| [array]::Reverse() with clone | O(n) | O(n) | Fast in-place reversal on a copy |
| For loop manual build | O(n) | O(n) | Learning and custom logic |
Use negative indices with range
-1..-($array.Length) for a quick and clean array reversal.Trying to reverse the array directly with
[array]::Reverse() without cloning modifies the original array.