Author Posts

September 18, 2013 at 8:48 am

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?

September 18, 2013 at 9:01 am

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'.
}

September 18, 2013 at 9:25 am

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.