DevOps | Scripts | Automation

Powershell

How to validate the set in PowerShell?

To add the validation set functionality into PowerShell, we can use the ValidateSet parameter. Before going into further explanation, let’s take an example. Suppose we have three colors (Red, Green, and Yellow) to validate from the input then how generally we write the program,

param(
    [Parameter(Mandatory)]
    [String]$ColorName
)

$colors = @("Red","Yellow","Green")

if($colors -contains $ColorName){
   Write-Host "Color name is valid" -f Green
}
else{
    Write-Host "Color name is invalid" -f Red
    return
}

Output:

What if we could validate this set at the first instance when the script started execution and if the user enters the wrong choice other than the set then we can terminate the script. There is a ValidateSet parameter available for this. There are two benefits of it, first, we don’t need to write the additional steps, and second, there will be a tab-completion feature for the sets that exist.

param(
    [Parameter(Mandatory)]
    [ValidateSet("Red","Yellow","Green")]
    [String]$ColorName
)

Write-Output "$ColorName is valid color name"

When we run the script in ISE you will get the available values in the set and in the PowerShell console, you need to press the tab button in order to get the different item from the set each time.

If the color name, doesn’t exist then,

It says the entered color name is not among the set. If you are using the PowerShell 6+ version then you can add the ErrorMessage attribute in the ValidateSet parameter.

param(
    [Parameter(Mandatory)]
    [ValidateSet("Red","Yellow","Green", ErrorMessage="Invalid value")]
    [String]$ColorName
)

Write-Output "$ColorName is valid color name"

Output: