powershell - 按名称将管道输入发送到不匹配的属性名称

标签 powershell

我有一个函数,它创建一个属性名称为“事件编号”的对象:

Function Get-ID {
    New-Object -TypeName PSObject -Property @{'Incident Number' = 'INC12345'; 'Other Stuff' = 'Blah'}
}

我想通过管道将该“事件编号”值发送到另一个函数,但在第二个函数中,输入属性被命名为“ID”:

Function Get-Note {
    Param(
        [Parameter(ValueFromPipeline)]
        [string]$ID
    )
    Write-Output "The input was $ID"
}

虽然可以使用带有空格的变量名称(例如 ${Incident Number}),但这使得在命令行中用作参数变得很尴尬。

按照上面的定义,输出是:

The input was @{Other Stuff=Blah; Incident Number=INC12345}

使用[Parameter(ValueFromPipelineByPropertyName)]返回:

Get-Note : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

仅供引用 - 以上是一个示例。实际上,第一个函数创建的对象的属性是由 API 调用确定的。虽然我可以将这些属性重命名为该函数的一部分,但我的偏好是让它们保持 API 的定义。

最佳答案

我发现可以通过使用[Alias()]参数属性来做到这一点:

Function Get-ID {
    New-Object -TypeName PSObject -Property @{'Incident Number' = 'INC12345'; 'Other Stuff' = 'Blah'}
}

Function Get-Note {
    Param(
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        [Alias('Incident Number')]
        [string]$ID
    )
    Write-Output "The input was $ID"
}

输出:

PS > Get-ID | Get-Note

The input was INC12345

关于powershell - 按名称将管道输入发送到不匹配的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44156868/

相关文章:

azure - 无法使用 Azure PowerShell 注册 Microsoft.DataFactory

powershell - Get-ChildItem递归排除不排除文件夹

powershell - 如何使用 Powershell 输出到 Ansible Playbook 中

powershell - 使用 PowerShell 对列表中的每个目录运行命令

windows - 与Linux等效的Windows:查找-name

azure - 在Powershell中获取azure资源的标签值

bash - 将两个 shell 命令组合成一个命令

powershell - 如何使用多个参数仅在PowerShell中强制高级功能的位置0

sql-server - 如何使用powershell运行sql脚本?

rest - 通过 Powershell 中的 REST API 调用下载 ZIP 内容