
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use 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
Advertisements