开发者

How to rename an alias in PowerShell?

I want to make my own versions of some of the builtin PowerShell aliases. Rather than completely removing the overridden aliases, I'd like to rename them so I can still use them if I want to. For example, maybe I'll rename set to orig_set and then add my own new definition for set.

This is what I've tried so far:

PS> alias *set*

CommandType     Name     Definition
-----------     ----     ----------
Alias           set      Set-Variable

PS> function Rename-Alias( $s0, $s1 ) { Rename-Item Alias:\$s0 $s1 -Force }
PS> Rename-Alias set orig_set
PS> alias *set*

开发者_StackOverflowCommandType     Name     Definition
-----------     ----     ----------
Alias           set      Set-Variable

Any ideas as to why this isn't working?


The beauty of the provider system in PowerShell is that you can use good ol' Rename-Item on alias because there is an alias drive e.g:

Rename-Item Alias:\set original_set -Force

That is, you learn how to use Get-ChildItem, Remove-Item, Copy-Item, etc and you can apply them to things other than directories and files - as long as the "thing" is contained in a provider. To see all your providers execute:

Get-PSProvider

To see all the drives created from these providers execute:

Get-PSDrive


function Rename-Alias($old, $new)
{
    $resolved = get-alias $old
    $cmdletName = $resolved.definition
    Set-Alias $new $cmdletname
    rm "alias:\$old" -force
}


One solution: change how you call the Rename-Alias function. Instead of

PS> Rename-Alias set orig_set

do this:

PS> . Rename-Alias set orig_set

[Thanks to @Keith Hill for this tip.]

But this begs the question: how can one write a function to rename aliases without needing to always be called with dot (.)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜