Reverse elements via pipeline

Is there a function that reverses elements passed via pipeline?

E.g.:

PS C:\> 10, 20, 30 | Reverse
30
20
10
1

9 Answers

You can cast $input within the function directly to a array, and then reverse that:

function reverse
{ $arr = @($input) [array]::reverse($arr) $arr
}
10, 20, 30 | Sort-Object -Descending {(++$script:i)}
5

Here's a remarkably compact solution:

function Reverse
{ [System.Collections.Stack]::new(@($input))
}

Here's one approach:

function Reverse ()
{ $arr = $input | ForEach-Object { $_ } [array]::Reverse($arr) return $arr
}

Using $input works for pipe, but not for parameter. Try this:

function Get-ReverseArray { Param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeLine = $true)] $Array ) begin{ $build = @() } process{ $build += @($Array) } end{ [array]::reverse($build) $build }
}
#set alias to use non-standard verb, not required.. just looks nicer
New-Alias -Name Reverse-Array -Value Get-ReverseArray

Test:

$a = "quick","brown","fox"
#--- these all work
$a | Reverse-Array
Reverse-Array -Array $a
Reverse-Array $a
#--- Output for each
fox
brown
quick
$array = 10,20,30; (($array.Length - 1)..0) | %{ $array[$_] }

I realize this doesn't use a pipe, but I found this easier if you just wanted to do this inline, there is a simple way. Just put your values into an array and call the existing Reverse function like this:

$list = 30,20,10
[array]::Reverse($list)
# print the output.
$list

Put that in a PowerShell ISE window and run it the output will be 10, 20, 30.

Again, this is if you just want to do it inline. There is a function that will work for you.

You can use Linq.Enumerable.Reverse, but it's hard work. Either of the following work:

,(10, 20, 30) | % { [Linq.Enumerable]::Reverse([int[]]$_) }
,([int[]]10, 20, 30) | % { [Linq.Enumerable]::Reverse($_) }

The two challenges are putting the whole array into the pipeline rather than one element at a time (solved by making it an array of arrays with the initial comma) and hitting the type signature of Reverse (solved by the [int[]]).

Try:

10, 20, 30 | Sort-Object -Descending
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like