Using Parameter [ValidateSet()]

I recently wanted to check a function parameter against a small set of valid values.  The Advanced Function parameter option [ValidateSet()] is exactly what’s needed, but I’d like to suggest an enhancement.

Suppose I have a function that lets a user pick from a pre-defined range of colours.  I could use this:

Function Get-Colour {

    Param (
        [Parameter(Position=0)]
        [ValidateSet('Red','Blue','Green')]
        [String]
        $Colour='Blue'
    )

#   ... rest of code

}

This is great; but consider the way that PowerShell handles parameter names by default;  when I call a function or cmdlet then as long as I make my parameter names long enough to be unique that’s good enough.  So I can say “Get-Colour –Colour Blue”  or “Get-Colour –c Blue” (in this case I can also say “Get-Colour Blue” as well) – all work as expected.

I’d like to suggest that [ValidateSet()] optionally enables this ability to shorten parameters (in this case it’s actually the arguments).  I could then say something like:

Function Get-Colour {

    Param (
        [Parameter(Position=0)]
        [ValidateSetAllowAbbreviation('Red','Blue','Green')]
        [String]
        $Colour='Blue'
    )

#   ... Rest of code

}

Allowing me to call the function with “Get-Colour r” or “Get-Colour g” and so on.

This allows me to still tightly constrain the possible argument values but without requiring that whoever calls the function has to type the fully qualified argument name.

If you think this might be a useful enhancement please vote for it on connect Here (note: you need a Live id to vote on the connect site).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s