我有一个函数,它创建一个属性名称为“事件编号”的对象:
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/