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.
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.
Function Order-Breakfast {
Param (
[ValidateSet("apple","orange","banana")]
[String]$Fruit
)
$Fruit
} 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:
Test : Cannot validate argument on parameter 'Fruit'. The argument "apple orange" does not belong to the set "apple,orange,banana" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
At line:1 char:13
+ test -fruit apple,orange
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test], ParameterBindingValidationException 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.
Function Order-Breakfast {
Param (
[ValidateSet("apple","orange","banana")]
[ValidateCount(1,1)]
[String[]]$Fruit
)
$Fruit
} 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:
Order-Breakfast : Cannot validate argument on parameter 'Fruit'. The number of provided arguments, (2), exceeds the maximum number of allowed arguments (1). Provide fewer than 1 arguments, and then try the command again.
At line:1 char:24
+ order-breakfast -fruit apple,apple
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Order-Breakfast], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Order-Breakfast This seems to accomplish the goal and the error message is a little more clear about what it is unhappy about.
2
u/xxdcmast Apr 15 '22
Thanks for the help. It seems there isnt really a clean way of doing this natively. Your idea comes close but you the request can be an array of multiple options, apple and banana is fine.
From the suggestions is thing the .tolower and select unique might be the best way forward. Thanks
2
u/Th3Sh4d0wKn0ws Apr 15 '22
oh man i completely skipped over the fact that we just don't want repeats. There is also the ValidateScript option. I'm on mobile or I'd whip something up.
1
u/neztach Apr 16 '22
When you aren’t on mobile, I’d be interested in the mock up. I’ve recently been researching how to about adding a validateset for a switch which apparently “isn’t possible” as a parameter, but surely I’m not inventing this wheel. I should probably also find a decent write up on how to make a parameter set where if you choose to use a given switch then it requires a string to follow it
1
u/Th3Sh4d0wKn0ws Apr 17 '22
i'm actually having a hard time making it work. ValidateScript utilizes the automatic variable $_ to represent the current object being fed to that parameter. When you feed multiple things to the parameter they still seem to get passed to the ValidateScript one at a time, so I'm not sure how to count them.
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 -unique4
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,Band will return:b a BAre 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 -unique3
2
3
u/PMental Apr 15 '22 edited Apr 21 '22
You could write the logic yourself using ValidateScript instead.
Edit: Spelling.
2
u/spyingwind Apr 16 '22
Can't,
$_only contains one item from the array. Can't access the parameter variable either from the ValidateScript block.function Get-ValidateSet { [CmdletBinding()] param ( [ValidateSet("A", "B")] [ValidateScript( { Write-Host "$Test,$_" $true } )] $Test ) begin {} process {$Test} end {} } Get-ValidateSet -Test "A", "B"Output:
,A ,B A B
3
u/NoConfidence_2192 Apr 16 '22
PowerShell Tip: When you want to limit available choices AND make sure each choice only counts once, create and use a flags enumeration instead of a ValidationSet. Based off your example you could do something like:
[flags()] enum BreakfastFruit {
Apple = 1
Orange = 2
Banana = 4
}
Function Get-BreakfastFruit {
Param (
[BreakfastFruit]$Fruit
)
$fruitOrderCount = @{
Apple = 0
Orange = 0
Banana = 0
}
switch ($Fruit) {
{$Fruit -band [BreakfastFruit]::Apple} {
$fruitOrderCount.Apple++
"Apple coming right up!"
}
{$Fruit -band [BreakfastFruit]::Orange} {
$fruitOrderCount.Orange++
"Orange coming right up!"
}
{$Fruit -band [BreakfastFruit]::Banana} {
$fruitOrderCount.Banana++
"Banana coming right up!"
}
Default {
"No fruit for breakfast!"
}
}
$fruitOrderCount
}Using a flags enum does take a bit of binary math. You can find a decent introduction to flags enums on Fun with PowerShell Enum Flags.
The cool thing about scripting is we all get to build our own solutions to any challenges we come across. That means endless opportunities for us all to learn from each other.
As always, keep learning, growing, experimenting, and having fun.
2
u/UnknownScorpion Apr 16 '22
Function Order-Breakfast {
Param (
[ValidateSet("Apple","Orange","Banana")]
[String[]]$Fruit
)
$FindDuplicates = $Fruit | Group-Object | Where-Object -Property Count -gt 1
if ($FindDuplicates) {
"Duplicate values were found: $($FindDuplicates.Name -join ', ')"
BREAK
}
"If duplicates weren't detected we continue on with the rest of script . . ."}
Order-Breakfast -Fruit orange, banana, banana
I can't get this to stay in a code block, so ridiculous!
2
u/KevMar Community Blogger Apr 18 '22
I would do the dedup inside the function once you have the value.
You can also change your logic so it doesn't matter.
$validFruit= "Apple","Orange","Banana"
foreach($fruitType in $validFruit){
if( $fruit -contains $fruitType ){...
22
u/Thotaz Apr 15 '22
Not with any of the existing validation attributes, but you can create your own that does this:
This will throw if you provide the same string twice (case insensitive).