Array is a collection of items. Sometimes we needed to reverse or inverse a array collection. There are many approaches available in PowerShell for doing the reverse or inverse operations but the approach talked in this article is most easiest one.
Reversing String Array using PowerShell
The [Array] accelerator in PowerShell has a static method called reverse() which can be used to reverse a array. This method really doesn’t distinguish whether it is string array, number array or any other kind of array. All it does is reversing it. Though array type is not a matter, I have given a examples for each array type below for better understanding.
$StringArray = @(“abc”,“xyz”,“thn”)
Reversing numeric array using PowerShell
Below is a example for reversing a numeric array using PowerShell.
$numbericarray = @(1,2,4,3,6,9,7)
Reversing Characters array using PowerShell
Below example is for reversing a characters array. Approach is similar to reversing number or string based arrays.
$chararray = @(‘a’,‘c’,‘g’,‘d’,‘r’)
Hope this article helps.
I have a strange behavior of Reverse method.
PS H:\> $StringArray = @(“abc”,“xyz”,“thn”)
$StringArrayR = $StringArray
So BOTH arrays are reversed. What’s wrong?
Basically Array class does not return anything, it just reverses the array elements and saves in same variable. in your example, you reversed the array and copied it to a new array. So both are same.
public static void Reverse(
If you want to just reverse and assign to someother variable and keep the existing array same, you may consider below example
$array = @(“abc”,”xyz”,”tuv”)
$arrayR = $array[($array.Length – 1)..0]
I don’t think your explanation is accurate. The 2nd array is reversed *after* it is copied to the other variable, not before. It would be like saying that if I do this:
$StringArray1 = @(“A”, “B”, “C”)
$StringArray2 = $StringArra1
$StringArray2 = @(“X”, “Y”, “Z”)
…now, both arrays would be X Y Z.
The command is to reverse the 2nd array, not the 1st one, yet both get reversed (I just tested it and got the same result).
Hi Abel, I didn’t get your question. There is no reverse method called in the code you shared. Am I missing anything?