How to use the ValidateSet Attribute in PowerShell function?


The ValidateSet attribute in PowerShell function is to validate the values entered from the set which means, it allows only specific values from the set. To understand better consider the below example, we have an array and we need to check if entered values are among array or not then we will use the below code.

Function PetAnimalsCheck {
   param(
      [String]$Animal
   )
   $Animals = "Cow","Dog","Cat","Horse","Camel","Elephant"
   if($Animals -contains $Animal) {
      Write-Output "Animal is in the list of Pet Animals"
   } else {
      Write-Output "Animal is not Pet Animal"
   }
}

Output

PS C:\> PetAnimalsCheck -Animal Dog
Animal is in the list of Pet Animals
PS C:\> PetAnimalsCheck -Animal Tiger
Animal is not Pet Animal

If we replace the above commands with the ValidateSet attribute, code will be of few lines.

Function PetAnimalsCheck {
   param(
      [ValidateSet("Cow","Dog","Cat","Horse","Camel","Elephant",ErrorMessage="Ani
      mal Name is not among list")]
      [String]$Animal
   )
   Write-Output "Animal is Pet Animal"
}

Output

PS C:\> PetAnimalsCheck -Animal Tiger
PetAnimalsCheck: Cannot validate argument on parameter 'Animal'. Animal Name is not among list
PS C:\> PetAnimalsCheck -Animal Cat
Animal is Pet Animal

If you need the set to Case sensitive, use the IgnoreCase value.

Function PetAnimalsCheck {
   param(
      [ValidatepathExi]
      [ValidateSet("Cow","Dog","Cat","Horse","Camel","Elephant",ErrorMessage="Ani
      mal Name is not among list or case sensitive", IgnoreCase=$false)]
      [String]$Animal
   )
   Write-Output "Animal is Pet Animal"
}

Output

PS C:\> PetAnimalsCheck -Animal cat
PetAnimalsCheck: Cannot validate argument on parameter 'Animal'. Animal Name is not among list or case sensitive
PS C:\> PetAnimalsCheck -Animal Cat
Animal is Pet Animal

Updated on: 19-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements