Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 300
dharmatech Avatar asked Mar 31 '14 20:03

dharmatech


4 Answers

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

function reverse
{ 
 $arr = @($input)
 [array]::reverse($arr)
 $arr
}
like image 99
mjolinor Avatar answered Nov 02 '22 05:11

mjolinor


10, 20, 30 | Sort-Object -Descending {(++$script:i)}
like image 37
David Avatar answered Nov 02 '22 07:11

David


Here's one approach:

function Reverse ()
{
    $arr = $input | ForEach-Object { $_ }
    [array]::Reverse($arr)
    return $arr
}
like image 2
dharmatech Avatar answered Nov 02 '22 07:11

dharmatech


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
like image 2
Michael Moynihan Avatar answered Nov 02 '22 06:11

Michael Moynihan