9

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?

1 Answer 1

14

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

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!
Not "non-existent," but rather "exists, but only used when no other parameter sets match."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.