r/PowerShell • • Apr 15 '22

Question PowerShell parameter validate set and removing already used options

I have a function with several parameters defined. One of the parameters is a validate set consisting of 3 items. This works as expected and the validation only allows the entry of those 3 items.

However where im getting tripped up on is that it seems like validate set will allow me to specify the same item multiple times. for example with the validate set below.

[ValidateSet("Apple","Orange","Banana")]

When entering data into the function the user can input an entry from the validate set multiple times.

 order-breakfast -fruit apple, apple, apple, banana

Is there a way to limit the validate set so that you can only enter apple once. Basically if the entry from validate set is used, remove it from the list of available options.

30 Upvotes

27 comments sorted by

View all comments

4

u/Szeraax Apr 15 '22

No, you can't. If you are doing it as [string[]] for your variable type, you'd need to de-duplicate the list after invocation.

4

u/i_me_me Apr 15 '22

To add a little to this answer:

Which is what I do in those cases by using the unique parameter of select-object in the function

$fruits = $fruits | select-object -unique

4

u/Szeraax Apr 15 '22

And to add insult to injury, I present Select-Object -Unique should be case insensitive.

This function:

function a {
    param(
        [ValidateSet("a", "b")]
        [string[]]$a
    )
    $a | Select-Object -Unique
}

Can be invoked as: a -a b,a,B and will return:

b
a
B

Are Apples and apples the same? Not according to Select -unique.

2

u/i_me_me Apr 15 '22

Good point, in that case I'd convert the input into a know and acceptable casing before calling the validation. I agree though, I'd like to see an iunique parameter for select object

$fruits = $fruits.toupper() | select-object -unique

3

u/Szeraax Apr 15 '22

Sadly, it should be cunique. Just like cmatch, cin, clike. :P

2

u/davesbrown Apr 15 '22

cool example, but man, 'a' bit confusing