Search code examples
powershell

Check for existence of parameter in function


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?


Solution

  • 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