I have a function as follows:
function T { Param ( [switch] $IsValueNameRegularExpression ) .. }
Normally to determine if a parameter exists you would do if ($Param)
, only seeing as this is a [switch]
, if the function is called as T -IsValueNameRegularExpression:$false
will return false on if ($IsValueNameRegularExpression)
, even though the parameter exists - i.e., the caller specified a value to the optional parameter.
If I change the parameter type from [switch]
to [bool]
the same thing will happen, obviously.
In the code for my function I call some .NET methods which contain a default setting for my [bool]
`[switch]` parameters, so unless the user has specified a value (be it true or false) I don't want to pass it to the .NET method.
I could assign default values to the parameter to match those of the default value of the .NET method, but that would be assuming that the default value of the .NET method never changes, which might not be true ...
So, is there a more elegant way of doing this?
To check if a parameter is provided to a function, use the typeof operator to check if the parameter is not equal to the string "undefined" , e.g. if (typeof param !== 'undefined') . If the condition is met, the parameter was provided to the function.
You can use inspect. getargspec() to see what arguments are accepted, and any default values for keyword arguments. inspect. getargspec() should be considered deprecated in Python 3.
Parameter values to functions are stored on the stack as well, pushed immediately before the return address. Everything what lives on the stack (local variables, parameters etc.) can live in registers as well. That's why the C standard doesn't state explicitly what to store where.
For example, if one defines a function as def f(x): ... , then x is the parameter, and if it is called by a = ...; f(a) then a is the argument. A parameter is an (unbound) variable, while the argument can be a literal or variable or more complex expression involving literals and variables.
Use $PSBoundParameters.ContainsKey()
in order to check for a parameter presence:
function T { Param ( [switch] $IsValueNameRegularExpression ) $PSBoundParameters.ContainsKey('IsValueNameRegularExpression') } T T -IsValueNameRegularExpression T -IsValueNameRegularExpression:$false
Output:
False True True
An easier (and more accurate way) is to use the IsPresent property. Using roughly the same code:
function T { Param ( [switch] $IsValueNameRegularExpression ) $IsValueNameRegularExpression.IsPresent } T T -IsValueNameRegularExpression T -IsValueNameRegularExpression:$false
yields the following output:
False True False
Note that binding the switch to false makes it "not present"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With