参数验证基础
PowerShell 提供多种参数验证属性来确保输入合规性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Get-UserInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidatePattern("^[a-zA-Z]\\w{3,20}$")] [string]$UserName,
[ValidateSet('Active','Disabled','Archived')] [string]$Status = 'Active',
[ValidateRange(18,120)] [int]$Age ) }
|
验证类型详解
- Mandatory验证:
1 2
| [Parameter(Mandatory=$true, HelpMessage="请输入用户ID")] [string]$UserID
|
- 正则表达式验证:
1 2
| [ValidatePattern("^\\d{4}-\\d{2}-\\d{2}$")] [string]$BirthDate
|
- 脚本块验证:
1 2 3 4 5 6 7
| [ValidateScript({ if ($_ -notmatch "^CN=") { throw "必须使用LDAP格式" } $true })] [string]$DistinguishedName
|
最佳实践
- 组合使用多个验证属性
- 为复杂验证添加帮助信息
- 在验证失败时提供友好提示
- 优先使用内置验证属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function Register-Device { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateScript({ if (-not (Test-Path $_)) { throw "证书文件不存在" } $true })] [string]$CertPath ) }
|