Reverse an array

Ever needed to reverse an array?

If its 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 reveresed and $newary is empty!

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

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s