20

Is there a function that reverses elements passed via pipeline?

E.g.:

PS C:\> 10, 20, 30 | Reverse
30
20
10
dharmatech
  • 8,979
  • 8
  • 42
  • 88
  • As a pipleline only handles one object at a time you need to reverse the array before sending it to the pipe. – Dennis Dec 28 '22 at 11:33

9 Answers9

25

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

function reverse
{ 
 $arr = @($input)
 [array]::reverse($arr)
 $arr
}
mjolinor
  • 66,130
  • 7
  • 114
  • 135
8
10, 20, 30 | Sort-Object -Descending {(++$script:i)}
David
  • 115
  • 1
  • 1
2

Here's one approach:

function Reverse ()
{
    $arr = $input | ForEach-Object { $_ }
    [array]::Reverse($arr)
    return $arr
}
dharmatech
  • 8,979
  • 8
  • 42
  • 88
2

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
2
$array = 10,20,30; (($array.Length - 1)..0) | %{ $array[$_] }
Alexey Gusarov
  • 337
  • 2
  • 9
2

Here's a remarkably compact solution:

function Reverse
{
    [System.Collections.Stack]::new(@($input))
}
jmik
  • 311
  • 2
  • 10
1

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.

CodeChops
  • 1,980
  • 1
  • 20
  • 27
0

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[]]).

phuclv
  • 37,963
  • 15
  • 156
  • 475
Lamarth
  • 506
  • 4
  • 12
-4

Try:

10, 20, 30 | Sort-Object -Descending
Silviu
  • 298
  • 2
  • 10
  • 10
    This works if you also want to sort at the same time, but if you don't want to sort, this won't work. (E.g, maybe your original array was `20,10,30` and you want `30,10,20`) – jpmc26 Jan 06 '16 at 18:23