How to use the ValidateRange attribute in PowerShell function?

PowerShellMicrosoft TechnologiesSoftware & Coding

Validation parameters are a set of rules that you define on the PowerShell variable and restrict users from entering some values and binding users to enter values in the specific domain. If there are not validation parameters the script would be lengthy. The ValidateRange attribute is one of them.

ValidateRange Attribute

This parameter is to validate the specific range of numbers. For example, If we need users to enter a value between 5 and 100 and we simply write the script using the If/else statement as shown below.

function AgeValidation {
   param(
      [int]$age
   )
   if(($age -lt 5) -or ($age -gt 100)) {
      Write-Output "Age should be between 5 and 100"
   }
   else{
      Write-Output "Age validated"
   }
}

Output−

PS C:\> AgeValidation -age 4
Age should be between 5 and 100
PS C:\> AgeValidation -age 55
Age validated

The above code works but we don’t need the user to enter the wrong age at all and throw the error when he enters the wrong age. This can be achieved by writing a few more lines again but through validaterange we can achieve our goal without writing more lines.

function AgeValidation {
   param(
      [ValidateRange(5,100)]
      [int]$age
   )
   Write-Output "Age validated!!!"
}

Output−

PS C:\> AgeValidation -age 3
AgeValidation: Cannot validate argument on parameter 'age'. The 3 argument is les
s than the minimum allowed range of 5. Supply an argument that is greater than or
equal to 5 and then try the command again.
PS C:\> AgeValidation -age 150
AgeValidation: Cannot validate argument on parameter 'age'. The 150 argument is g
reater than the maximum allowed range of 100. Supply an argument
that is less than or equal to 100 and then try the command again.

When you enter an age below or above allowed values, the script throws an error. This is how we can use the ValidateRange attribute.

raja
Published on 19-Sep-2020 08:49:59
Advertisements