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

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.