Processing Function Parameters As Hash Table

by Nov 19, 2010

If you want to get more control over function parameters, you can treat them as hash table. So in your function, you can then check whether a certain parameter was specified by the caller, and then act accordingly:

function Do-Something {
[CmdletBinding()]
param(
$name,
$surname = "Default",
$age,
$id
)

# treat all submitted parameters as hashtable:
$params = $PSCmdlet.MyInvocation.BoundParameters

# act in response of submitted and omitted parameters:
if ($params.ContainsKey('name')) {
'You specified -name and submitted {0}' -f $params['name']
} else {
'You did not specify -name'
}
}

Do-Something

You did not specify -name

Do-Something -id 1

You did not specify -name

Do-Something -name weltner

You specified -name and submitted weltner

Twitter This Tip!
ReTweet this Tip!