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

Welcome Forums General PowerShell Q&A 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

 
Participant
5 years, 2 months ago.

  • Author
    Posts
  • #10220

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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.

The topic ‘parameter: how to require either one or the other but not both’ is closed to new replies.