如何在 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 属性。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP