Enum like switch parameter in PowerShell

I would use a ValidateSet parameter attribute instead.

From: about_Functions_Advanced_Parameters

The ValidateSet attribute specifies a set of valid values for a parameter or variable. Windows PowerShell generates an error if a parameter or variable value does not match a value in the set.

Example function:

function test-value
{
    param(
        [Parameter(Position=0)]
        [ValidateSet('word','excel','powerpoint')]
        [System.String]$Application,

        [Parameter(Position=1)]
        [ValidateSet('v2007','v2010')]
        [System.String]$Version
    )


    write-host "Application: $Application"
    write-host "Version: $Version"
}   


PS > test-value -application foo

Output:

test-value : Cannot validate argument on parameter 'Application'. The argument "foo" does not belong to the set "word,excel,powerpoint" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.


You can use the ValidateSet attribute:

function My-Func
{
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('Word', 'Excel', 'PowerPoint', 'v2007', 'v2010', 'x86', 'x64')]
        [String]$MyParam
    )

    Write-Host "Performing action for $MyParam"
}

My-Func -MyParam 'Word'
My-Func -MyParam 'v2007'
My-Func -MyParam 'SomeVal'

Output:

Performing action for Word
Performing action for v2007
My-Func : Cannot validate argument on parameter 'MyParam'. The argument "SomeVal" does not belong to the set "Word,Excel,PowerPoint,v2007,v2010,x86,x64" specified by the ValidateSet attribute. Supply an argument that is in the
 set and then try the command again.
At C:\Users\George\Documents\PowerShell V2\ValidateSetTest.ps1:15 char:17
+ My-Func -MyParam <<<<  'SomeVal'
    + CategoryInfo          : InvalidData: (:) [My-Func], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,My-Func

Tags:

Powershell