Is there a way to add Alias to Powershell Cmdlet p

2019-05-09 10:58发布

问题:

I am writing custom Powershell cmdlets for my application and I need to provide Aliases to some cmdlets. So lets say I have cmdlet Get-DirectoryListing and I want to add Alias (say 'gdl') to this cmdlet. How can I do this?

The AliasAttribute doesn't work here, since it works only with Properties, Indexers or Field declarations. Also I know we can use Set-Alias command, but don't know where to put it.

Is it possible to programmatically add multiple aliases to a cmdlet?

回答1:

You need to create a psm1 file (powershell module) where you specific your dll with yours cmdlets to load and add aliases in this way:

In your module folder ( Get-ModuleFolder give a list of all if you have more that the default one, in my example I use the first one) create a folder with same name of your .dll and a SameNameOfYourDll.psm1 with this content:

Import-module "$((Get-ModulePath)[0])mycustomcmdlet\mycustomcmdlet.dll"
set-alias gdl Get-DirectoryListing -scope Global

For more raffinate module building look also at module manifest

Module manifest is the preffered way for .dll with custom cdmlets.