4

I am trying to create a function in PowerShell where there is a particular Parameter Switch that then gives other choices, but these are only available for use if this parameter is used in conjunction with the main one. This will be for adding users to AD groups. I am still learning how ParameterSets work.

What I want is for something like this to be possible:

OK: (where 21 and 22 are the multiple choice switches

Set-UserAccess -user Username -Access1 -Access2 -Access21
Set-UserAccess -user Username -Access1 -Access2 -Access21 -Access22
Set-UserAccess -user Username -Access1 -Access2 -Access22
Set-UserAccess -user Username -Access2 -Access22

Not OK:

Set-UserAccess -user Username -Access1 -Access21
Set-UserAccess -user Username -Access1 -Access2
Set-UserAccess -Access21

Can you please advise how to create the Parameter Sets to allow this.

Basically what I have so far is (renamed to be generic for this question)

[CmdletBinding(DefaultParameterSetName='Default')]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)][string[]]
$user,
[Parameter()][switch]$Access1,
[Parameter()][switch]$Access2,
[Parameter()][switch]$Access3,
[Parameter(ParameterSetName='Access4')][Switch]$Access4,
[Parameter(ParameterSetName='Access4')][Switch]$Access4Choice1,
[Parameter(ParameterSetName='Access4')][Switch]$Access4Choice2,
)

Please advise if any of this needs clarifying.

1 Answer 1

4

You could define a parameter set for each multiple choice switch (Access4, 5 and 6). However, I would use a string as Parameter with a ValidateSet:

[CmdletBinding(DefaultParameterSetName='Default')]
Param
(
    [Parameter(Mandatory=$true,
    ValueFromPipelineByPropertyName=$true,
    Position=0)][string[]]
    $user,
    [switch]$Access1,
    [switch]$Access2,
    [switch]$Access3,
    [ValidateSet("Access4Choice1", "Access4Choice2", "Access4Choice3")]
    [string]$Access4
)

This will give your a choice of the parameter: enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Just checking though, for that setup, can I choose multiple choices, or is that just a single choice? As that is required here.
You have to choice one of the strings within the validate set.
Or make it [string[]]$Access4 (ISE doesn't show menu for 2nd parameter, but TAB Works)
Thanks Frode, I should have thought of that.And thanks Martin. Looks like that will work. I hadn't come across validated sets yet in my learning and research
You are welcome. You may want to take a look at about_Functions_Advanced_Parameters. Please consider to accept the answer using the green checkmark.

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.