如何在PowerShell函数中使用ValidateRange属性?

验证参数是您在PowerShell变量上定义的一组规则,它们限制用户输入某些值,并限制用户在特定域中输入值。如果没有验证参数,脚本将很长。该ValidateRange属性就是其中之一。

ValidateRange属性

此参数用于验证数字的特定范围。例如,如果我们需要用户输入5到100之间的值,我们只需使用If / else语句编写脚本,如下所示。

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"
   }
}

输出-

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

上面的代码有效,但是我们根本不需要用户输入错误的年龄并在输入错误的年龄时抛出错误。这可以通过再写几行来实现,但是通过validaterange我们可以在不写更多行的情况下实现我们的目标。

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

输出-

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.

当您输入的年龄小于或等于允许值时,脚本将引发错误。这就是我们可以使用ValidateRange属性的方式。