r/PowerShell • u/xxdcmast • 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, bananaIs 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
2
u/Th3Sh4d0wKn0ws Apr 15 '22 edited Apr 15 '22
My first thought was to cast your parameter variable specifically as a single string, and therefore to not allow an array.
By using '[String]' you're staying that the variable $Fruit can only ever be a single thing. It will throw this error text if you try to pass it more than one value from that set:
which admittedly isn't super clear. But if you change the object cast to '[String[]]' you're stating that it will accept and array of input, and it will then accept multiple values.
EDIT
another way to do this would be to use the '[ValidateCount()]' parameter attribute.
Even though I'm saying that the $Fruit variable will accept and array of values i've specified the ValidateCount attribute to say that the minimum number of values is 1, and the max is 1. If I provide two values the error message is:
This seems to accomplish the goal and the error message is a little more clear about what it is unhappy about.