7

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?

bwerks
  • 8,651
  • 14
  • 68
  • 100

1 Answers1

11

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"
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • To verify this, I also added `"ParameterSetName: $($PSCmdlet.ParameterSetName)"` to verify, and it works as you suggested. However, per my description, piping $null to this function also fails, but when I stepped back to consider what that means my requirements didn't make sense: piping a value to a parameter set with no parameters is a contradiction. It's good to know that specifying non-existent parameter sets does work though. Thanks! – bwerks Dec 21 '17 at 22:47
  • Not "non-existent," but rather "exists, but only used when no other parameter sets match." – Bill_Stewart Dec 21 '17 at 23:01