powershellparameter-sets

Is there some way to define a parameterless powershell parameter set?


I've got some fairly complex functions that I'm writing for a library module, with lots of different ways it can be called. However, it is in fact possible to default all of them, but when I try to call my function with no parameters the call fails because the parameter set cannot be determined.

I would like to define a parameter set that contains no parameters whatsoever, such that calls with no parameters succeed. This is difficult to do since ParameterSetName is a property of the Parameter attribute though, and it's not possible to attribute nothing.

I experimented with the DefaultParameterSet property of the CmdletBinding attribute that is placed on the param block, however nothing seemed to work. It seems that the parameter set name defined there must actually exist in order for Powershell to default to it.

Currently my best approximation of this use case is to define one of the parameter sets to have no Mandatory parameters, however these fail when empty strings or nulls are piped in, and I would like for this not to be the case.

Is this possible?


Solution

  • Sure is. Just specify a default parameter set name that isn't used otherwise:

    function Foo {
        [CmdletBinding(DefaultParameterSetName='x')]
        Param(
            [Parameter(Mandatory=$true, ParameterSetName='y')]$a,
            [Parameter(Mandatory=$false, ParameterSetName='y')]$b,
            [Parameter(Mandatory=$true, ParameterSetName='z')]$c,
            [Parameter(Mandatory=$false)]$d
        )
    
        "`$a: $a"
        "`$b: $b"
        "`$c: $c"
        "`$d: $d"
    }