≡ Menu

Reversing a array using PowerShell

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”)

$StringArray

[array]::Reverse($StringArray)

$StringArray

Reversing String Array

Reversing String Array

Reversing numeric array using PowerShell

Below is a example for reversing a numeric array using PowerShell.

$numbericarray = @(1,2,4,3,6,9,7)

$numbericarray

[array]::Reverse($numbericarray)

$numbericarray

Reversing Numeric array

Reversing Numeric array

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’)

$chararray

[array]::Reverse($chararray)

$chararray

 

Reversing Char array

Reversing Char array

Hope this article helps.

 

 

{ 2 comments… add one }
  • Tim June 23, 2018, 12:55 am

    Hi!
    I have a strange behavior of Reverse method.

    PS H:\> $StringArray = @(“abc”,“xyz”,“thn”)
    $StringArray
    $StringArrayR = $StringArray
    [array]::Reverse($StringArrayR)
    $StringArray
    $StringArrayR

    abc
    xyz
    thn
    thn
    xyz
    abc
    thn
    xyz
    abc

    So BOTH arrays are reversed. What’s wrong?
    Thanks.

    • Chandrasekhar Reddy July 2, 2018, 2:27 pm

      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(
      Array array
      )

      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”)
      #[System.Array]::Reverse($array)
      $arrayR = $array[($array.Length – 1)..0]
      $array
      $arrayR

Leave a Comment