PowerTip: Use PowerShell to Reverse Array


Summary: Easily use Windows PowerShell to reverse an array.

Hey, Scripting Guy! Question How can I use Windows PowerShell to reverse an array?

Hey, Scripting Guy! Answer Pipe the array to the Sort-Object cmdlet and use the –Descending switch, for example:

$a = 1,2,3,4,5

$b = $a | sort -Descending

Comments (4)

  1. John Ludlow says:

    That doesn’t really reverse the array, because if the original array was out of order (say, 1,3,2) then you’d expect the result to be out of order, but in reverse (2,3,1). In your example, you’d end up with the items sorted, in descending order.

    Something like this would reverse the array:

    $b = $a
    [array]::Reverse($b) # it’s an out parameter

  2. Jon Wolthuis says:

    As John pointed out, this answer is wrong. Reversing position is different than sorting high-to-low. Try $a = 5,3,4,1,2.

  3. Larry Weiss says:

    # here is one PowerShell way to reverse an array just for the fun of it
    # for very large arrays, building the interim string $b would get expensive
    # for practical use, the [array]::Reverse($b) way shown by John Ludlow would be best
    #
    <#c:#> $a = 5,3,4,1,2
    <#c:#> $b=”
    <#c:#> for($n=-1;$n -ne -($a.length+1);$n–){$b=$b+"`$a[$n],"}
    <#c:#> $b=$b[0..($b.length-2)]-join”
    <#c:#> $b = (iex $b)
    <#c:#> $b
    2
    1
    4
    3
    5

  4. Larry Weiss says:

    # or this version, that is obviously simpler than what I posted earlier
    <#c:#> $a = 5,3,4,1,2
    <#c:#> $b = $a[ ($a.Length-1) .. 0]
    <#c:#> $b
    2
    1
    4
    3
    5

Skip to main content