【问题标题】:Declaring multiple aliases in an advanced PowerShell function在高级 PowerShell 函数中声明多个别名
【发布时间】:2018-06-27 21:40:02
【问题描述】:

用于在 PowerShell cmdlet 中声明别名的 documentation 显示如下:

Function Get-SomeValue {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)]
        [Alias("MachineName")]
        [string[]]$ComputerName
    )

    Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName
}

我使用什么语法来创建多个别名?

  • [Alias("one","two","three)]
  • [Alias("one")][Alias("two")][Alias("three")]
  • 以上都不是
  • 还有别的吗?

附:使用Get-Help 时,应该在哪里显示别名?到目前为止,我还没有看到它们。

【问题讨论】:

    标签: powershell syntax alias


    【解决方案1】:

    [Alias("one")][Alias("two")][Alias("one", "two")] 都可以工作。显示参数帮助时会看到别名:

    PS C:\> Get-Help Get-SomeValue -Parameter computername -计算机名 必需的?真的 位置? 0 接受管道输入?真(按值) 参数集名称(全部) 别名一、二 动态的?错误的

    【讨论】:

      【解决方案2】:

      补充 Ansgar Wiechers' helpful answer:

      如果文档不足,您可以自己检查底层属性类,假设您熟悉 C#:

      [Alias(...)] 暗示System.Management.Automation 命名空间中的类AliasAttribute,即System.Management.Automation.AutomationAttribute

      如果您在 https://docs.microsoft.com/en-us/dotnet/api 查找该类,您会发现 https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.aliasattribute?view=powershellsdk-1.1.0,其构造函数具有以下签名:

      public AliasAttribute (params string[] aliasNames);

      这告诉您多个别名可以作为单独的参数传递给[Alias(...)]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-19
        • 2017-06-16
        • 2015-09-16
        • 2019-04-07
        • 2021-03-04
        • 2012-04-05
        相关资源
        最近更新 更多