简体   繁体   中英

Set-Alias fails for value with a space character in it

I want to use ⍋ to sort ascending , and use ⍒ to sort descending .

I successfully set ⍋ as an alias for sort (default is ascending):

Set-Alias -Name ⍋ -Value Sort-Object

I failed to set ⍒ to an alias for sort descending:

Set-Alias -Name ⍒ -Value Sort-Object -Descending

Here is the error message I received:

Set-Alias : A parameter cannot be found that matches parameter name 'Descending'.
    At line:1 char:38
    + Set-Alias -Name ⍒ -Value Sort-Object -Descending
    +                                      ~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Alias], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetAliasCommand

Any help would be appreciated.

You can not set aliases that include parameters. You need to create a function that wraps the cmdlet.

function Sort-ObjectDescending
{
    [Alias("⍒")]

    param(
        [Parameter(Position = 0)]
        [Object[]]
        $Property,

        [Switch]
        $CaseSensitive,

        [String]
        $Culture,

        [Switch]
        $Unique,

        [Parameter(ValueFromPipeline)]
        [PSObject]
        $InputObject
    )

    begin {
        try {
            $scriptCmd = { Sort-Object -Descending @PSBoundParameters }
            $steppablePipeline = $scriptCmd.GetSteppablePipeline()
            $steppablePipeline.Begin($PSCmdlet)
        } catch {
            throw
        }
    }

    process {
        try { $steppablePipeline.Process($_) } catch { throw }
    }

    end {
        try { $steppablePipeline.End() } catch { throw }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM