Is there a function that reverses elements passed via pipeline?
E.g.:
PS C:\> 10, 20, 30 | Reverse
30
20
10
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)}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With