PowerShell for Windows Admins

Nov 8 2018   7:02AM GMT

Reverse an array

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

Ever needed to reverse an array?

If it’s sorted then sorting in the opposite direction will work. Most arrays aren’t sorted so you need to use the Reverse static method of the array class

Here’s some examples:

$carray = ‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’,’j’,’k’,’l’,’m’,’n’,’o’,’p’,’q’,’r’,’s’,’t’,’u’,’v’,’w’,’x’,’y’,’z’
$carray -join ‘,’
[array]::Reverse($carray)
$carray -join ‘,’

$iarray = 1,2,3,4,5,6,8,9,10
“$iarray”
[array]::Reverse($iarray)
“$iarray”

$psa = Get-Process p*
$psa
[array]::Reverse($psa)
$psa

The thing to note is that the array is reversed rather than creating output so if you do this:

$iarray = 1,2,3,4,5,6,8,9,10
$newary = [array]::Reverse($iarray)

$iarray is reversed and $newary is empty!

If you need the original and reversed arrays take a copy of the original and then reverse one of them.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: