parameter: how to require either one or the other but not both

This topic contains 2 replies, has 2 voices, and was last updated by  John Selph 4 years, 9 months ago.

  • Author
  • #10220

    John Selph

    So I'm making my first cmdlet and I'm using the chance to rewrite an old vbscript and improve it. I want to require either a username, or an employeeid parameter. I can't find the syntax for making param do this for me. Will I have to hand code it? Or is there a way to get it to do an either-or mandatory parameters?

  • #10222

    Dave Wyatt

    You can do this using parameter sets. By putting each parameter in one set and not the other, PowerShell will take care of the rest. You may want to define a default parameter set, as well:

    function YourCmdletName
        param (
            [Parameter(Mandatory = $true, ParameterSetName = 'ByUserName')]
            [Parameter(Mandatory = $true, ParameterSetName = 'ByEmployeeId')]
        # In the function's code, you can either test for whether $UserName and/or $EmployeedId are null, or
        # check $PSBoundParameters.ContainsKey('UserName'), or check $PSCmdlet.ParameterSetName to see whether it
        # is set to 'ByUserName' or 'ByEmployeeId'.
  • #10224

    John Selph

    Awesome, thanks for the quick answer. After watching both the MVA's on powershell, I'm really enjoying how much you can do with it. It's much better than vbscript.

You must be logged in to reply to this topic.