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.