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

22

u/Thotaz Apr 15 '22

Not with any of the existing validation attributes, but you can create your own that does this:

class ValidateUniqueStringsAttribute : System.Management.Automation.ValidateArgumentsAttribute
{
    [void]Validate([object]$Item, [System.Management.Automation.EngineIntrinsics]$engineIntrinsics)
    {
        $Set = [System.Collections.Generic.HashSet[string]]::new($Item.Count, [System.StringComparer]::OrdinalIgnoreCase)
        foreach ($String in $Item)
        {
            if (!$Set.Add($String))
            {
                throw [System.ArgumentException]::new()
            }
        }
    }
}
function Verb-Noun
{
    Param
    (
        [Parameter()]
        [ValidateSet("Hello", "Hi", "Bonjour")]
        [ValidateUniqueStrings()]
        [string[]]
        $Param1
    )
    Process
    {
        $Param1
    }
}

This will throw if you provide the same string twice (case insensitive).

3

u/xxdcmast Apr 15 '22

Im gonna have to dig into this one a bit to understand the class part.

2

u/UnknownScorpion Apr 16 '22

What's the trick to get code block to work right? I keep trying to get my code to stay in a block but reddit mangles it

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

3

u/Lee_Dailey [grin] Apr 16 '22

howdy UnknownScorpion,

when reddit is boofooing its own code formatting ... temporarily switch to Old.Reddit by replacing everything in the URL before the 1st dot with old.

that gives you the better control with the 4-spaces method ... and only does it that one time. [grin]

take care,
lee

2

u/UnknownScorpion Apr 16 '22

Thanks!

1

u/Lee_Dailey [grin] Apr 16 '22

howdy UnknownScorpion,

you are welcome! glad to be a bit of a help ... [grin]

take care,
lee

1

u/OPconfused Apr 19 '22

Why are you able to call [ValidateUniqueStrings()] in the param block?

I've never seen anything in a param block except [Parameter()] attributes, [ValidateSet/Range/Script/Pattern etc] attributes, or a type attribute.

[ValidateUniqueStrings()] isn't even the name of a method in the class. Is there a term for this I can look up to understand better how it works?

2

u/Thotaz Apr 19 '22

The term is Attributes. You can google Powershell custom validation attributes.
Tldr is that my class inherits from a special class that powershell expects. The reason it works despite the wrong name is that Powershell and C# has a special name lookup rule for attributes where it automatically appends "Attribute" to the class name.

1

u/OPconfused Apr 19 '22

Sweet, thanks! I didn't even know you could inherit from a native class. They always get blocked when I tried it, cool to see an exception.

2

u/Thotaz Apr 19 '22

They are probably getting blocked because they've been sealed. It's best to seal classes you don't intend end users to inherit from for performance reasons so the vast majority will be sealed.
If a Microsoft class is unsealed it's usually because it's been explicitly designed with inheritance in mind, like the ValidateArgumentsAttribute class where the whole point of that class is to act as a base class where the end user can write his own Validation code.

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 -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

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 ){...