<<< Back to Search

Scripting ::: Parameters ::: Input List (ValidateSet)

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.

Core Snippet

# Scripting ::: Parameters ::: Input List (ValidateSet) -_-
# PowerShellExamples.com

param
(
    # Parameter that enforce list options
    [parameter(Mandatory=$true)]
    [ValidateSet("Low", "Average", "High")]
    [String]$inputOption
)
    

Sample 1 : Enforcing Input List

# Sample 1 : Enforcing Input List
# Scripting ::: Parameters ::: Input List (ValidateSet) -_-
# PowerShellExamples.com

function Invoke-ParameterValidateSet {
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateSet("Low", "Average", "High")]
        [String]$inputOption
    )

    Write-Host "InputOption: $inputOption"
}


Write-Host "`r`n Calling Valid Option:  Expected Output of selected option" -ForegroundColor Green
Invoke-ParameterValidateSet -inputOption "Low"

Write-Host "`r`n `r`n Calling Wrong Option:  Expected error informing valid option list `r`n" -ForegroundColor Red
Invoke-ParameterValidateSet -inputOption "Min"


Result


  Calling Valid Option:  Expected Output of selected option
InputOption: Low
 
 Calling Wrong Option:  Expected error informing valid option list 

Invoke-ParameterValidateSet : Cannot validate argument on parameter "inputOption". The argument "Min" does not belong to the set "Low,Average,High" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the 
command again.
At line:21 char:42
+ Invoke-ParameterValidateSet -inputOption "Min"
+                                          ~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-ParameterValidateSet], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Invoke-ParameterValidateSet
 

Sample 2 : Enforcing Input List with Array String Parameter

# Sample 2 : Enforcing Input List with Array String Parameter
# Scripting ::: Parameters ::: Input List (ValidateSet) -_-
# PowerShellExamples.com

function Invoke-ParameterValidateSet {
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateSet("Low", "Average", "High")]
        [String[]]$inputOptions
    )

    Write-Host "InputOptions: $inputOptions"
}


Write-Host "`r`n Calling function with multiple values (Array String Parameter) " -ForegroundColor Green
Invoke-ParameterValidateSet -inputOptions "Low","High"



Result


 Calling function with multiple values (Array String Parameter) 
InputOptions: Low High