PowerShell can automatically bind values to parameters by data type matching. Here is a sample that shows what benefit this can be. Simply run this function:

function Test-Binding
{
    [CmdletBinding(DefaultParameterSetName='Date')]
    param
    (
        [Parameter(ParameterSetName='Integer', Position=0, Mandatory=$true)]
        [int]
        $Id,
        
        [Parameter(ParameterSetName='String', Position=0, Mandatory=$true)]
        [string]
        $Name,
        
        [Parameter(ParameterSetName='Date', Position=0, Mandatory=$true)]
        [datetime]
        $Date
    )
    
    $chosenParameterSet = $PSCmdlet.ParameterSetName
    Switch ($chosenParameterSet)
    {
        'Integer' { 'User has chosen Integer' } 
        'String'  { 'User has chosen String' } 
        'Date'    { 'User has chosen Date' } 
    }
       
    [PSCustomObject]@{
        Integer = $Id
        String = $Name
        Date = $Date
    }
}

Now a user can call Test-Binding and submit arguments:

 
PS C:\> Test-Binding "Hello"
User has chosen String

Integer String Date
------- ------ ----
      0 Hello      



PS C:\> Test-Binding 12
User has chosen Integer

Integer String Date
------- ------ ----
     12            



PS C:\> Test-Binding (Get-Date)
User has chosen Date

Integer String Date               
------- ------ ----               
      0        11/21/2017 11:44:33 AM
 

Twitter This Tip! ReTweet this Tip!

Anonymous