Accessing Function Parameters by Type

by Jun 29, 2010

Adding parameters to your functions is fairly easy. You can add a param() block and specify the parameters. But what if you wanted to assign values to different parameters based solely on type? Let's say you want a function that accepts both numbers and text, and depending on which type you submitted, choose a parameter. Here is how you can do that:

function Test-Binding {
[Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
[Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]

$set = $PSCmdlet.ParameterSetName
"You selected parameterset $set"

if ($set -eq 'ID') {
"The numeric ID is $id"
} else {
"You entered $name as a name"

Try this:

Test-Binding 12
Test-Binding "Hello"

Twitter This Tip! ReTweet this Tip!