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 Profile photo of John Selph John Selph 3 years, 7 months ago.

  • Author
    Posts
  • #10220
    Profile photo of John Selph
    John Selph
    Participant

    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
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    {
        [CmdletBinding(DefaultParameterSetName='ByUserName')]
        param (
            [Parameter(Mandatory = $true, ParameterSetName = 'ByUserName')]
            [System.String]
            $UserName,
    
            [Parameter(Mandatory = $true, ParameterSetName = 'ByEmployeeId')]
            [System.String]
            $EmployeeId
        )
    
        # 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
    Profile photo of John Selph
    John Selph
    Participant

    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.