我想要一个函数允许我传入设备ID或显示名称,并用它来做事。
在以下示例中,我传入了一个仅包含设备ID($obj.ID | Test-Function
)的客户PowerShell对象,但$DisplayName
和$Id
都以该值结束。
如何将值强制转换为正确的参数?
function Test-Function {
[CmdletBinding()]
Param (
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[string]$DisplayName
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[string]$Id
)
Begin {
#Code goes here
}
Process {
Write-Host "displayname is: $DisplayName" -ForegroundColor Green
Write-Host "displayname is: $Id" -ForegroundColor Green
}
}
答案 0 :(得分:3)
您可以使用ParameterSets解决此问题。注意我还修改了代码中的逗号和Write-Host
输出:
function Test-Function
{
[CmdletBinding()]
Param (
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='DisplayName'
)]
[string]$DisplayName,
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Id'
)]
[string]$Id
)
Begin {
#Code goes here
}
Process {
Write-Host "displayname is: $DisplayName" -ForegroundColor Green
Write-Host "Id is: $Id" -ForegroundColor Green
}
}
让我们试一试:
[PsCustomObject]@{Id = "hello"} | Test-Function
输出:
displayname is:
Id is: hello
和
[PsCustomObject]@{DisplayName = "hello"} | Test-Function
输出
displayname is: hello
Id is:
答案 1 :(得分:3)
只需删除ValueFromPipeline
并为false
属性设置$ Mandatory
,因此正确的解决方案是:
function Test-Function {
[CmdletBinding()]
Param (
[Parameter(
Mandatory=$false,
ValueFromPipelineByPropertyName=$true
)]
[string]$DisplayName,
[Parameter(
Mandatory=$false,
ValueFromPipelineByPropertyName=$true
)]
[string]$Id
)
Begin {
#Code goes here
}
Process {
Write-Host "displayname is: $DisplayName" -ForegroundColor Green
Write-Host "displayname is: $Id" -ForegroundColor Green
}
}