I recently read an email where someone was asking how they could check in their function if a value had been provided to one of the parameters. Consider for example,
001 |
function foo |
The usual way I’ve seen people deal this problem is by providing a default value which gets assigned to $x in the case that a value wasn’t provided by the caller and then checking for that value.
001 |
function foo |
That works in the majority of cases, but let’s say that you wanted to differentiate between a default $null value and $null being passed by the caller. What would you do?
If you’re on v2, a simple solution is to look at $PSBoundParameters. It’s a hashtable containing the parameters that were bound and what values were bound to them. Try this:
001 |
function foo |
PS >foo 1
Key Value
— —–
x 1
PS >foo 1 ‘foo’
Key Value
— —–
x 1
y foo
With $PSBoundParameters containing all the bound parameters, to check if a parameter was given a value, it’s a simple matter of checking if $PSBoundParameters contains a key for it.
001 |
function foo |
– Marcel Ortiz Soto [MSFT]
0 comments