Understanding Type-Based Parameter Binding

by Jul 14, 2016

PowerShell 2+

PowerShell can automatically bind arguments to parameters based on type. Simply define different parameter sets. Here is an example:

function Test-Binding
{
  #Content
  [CmdletBinding(DefaultParameterSetName='Number')]
  param
  (
    [String]
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName='Text', Position=0)]
    $Name,
  
    [int]
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName='Number',Position=0 )]
    $Length = -1
  )
  
  $set = $PSCmdlet.ParameterSetName
  "You called the function with the $set parameter set"
}


666 | Test-Binding
"Hello" | Test-Binding

When you call the function with a number, the “Number” parameter set is identified, and the argument is bound to the -Length parameter. If you submit a text, it ends up in the –Name parameter.

Using type-based parameter binding, your functions can deal with a variety of incoming information.

Twitter This Tip! ReTweet this Tip!