功能有两个"接受来自管道"参数

时间:2016-12-20 14:34:07

标签: powershell

我想要一个函数允许我传入设备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        
    }
}

2 个答案:

答案 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        
    }
}