Type-Based Parameter Binding (Part 2)

by Jul 15, 2016

PowerShell 2+

In a previous tip we introduced automatic type-based parameter binding. Here is a use case. The function Test-Binding accepts files and folders. For incoming files, it calculates the file size. For incoming folders, it emits a warning. Note how the parameter binding works per incoming element:

function Test-Binding
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName='File', Position=0)]
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName='Folder',Position=0 )]
    [Parameter(ParameterSetName='File', ValueFromPipelineByPropertyName)]
    if ($PSCmdlet.ParameterSetName -eq 'File')
      'File Size: {0:n1} MB' -f ($Length/1MB)
      Write-Warning "Folder ignored: $Folder"

Get-ChildItem c:\windows | Test-Binding -Verbose

Twitter This Tip! ReTweet this Tip!