有没有办法以编程方式将别名添加到Powershell Cmdlet? [英] Is there a way to add Alias to Powershell Cmdlet programmatically?

查看:99
本文介绍了有没有办法以编程方式将别名添加到Powershell Cmdlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的应用程序编写自定义Powershell cmdlet,我需要为某些cmdlet提供别名。因此,假设我有cmdlet Get-DirectoryListing,并且想向此cmdlet中添加Alias(例如 gdl)。我该怎么做?

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?

AliasAttribute在这里不起作用,因为它仅适用于属性,索引器或字段声明。我也知道我们可以使用Set-Alias命令,但是不知道将它放在哪里。

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.

是否可以通过编程方式向cmdlet添加多个别名?

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

推荐答案

您需要创建psm1文件( powershell模块)中,您可以使用自己的cmdlet来指定dll,以这种方式加载和添加别名:

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:

在您的模块文件夹中( Get-ModuleFolder 列出所有列表,如果您有更多的默认列表,请在例如,我使用第一个)创建一个具有与您的.dll相同名称的文件夹
和一个具有以下内容的 SameNameOfYourDll.psm1

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

模块清单是带有自定义cdmlets的.dll的首选方式

这篇关于有没有办法以编程方式将别名添加到Powershell Cmdlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆