如何在 PowerShell 中使用 ValidateLength 属性?
PowerShell 中的 ValidateLength 属性用于验证字符串的长度。通常,如果不使用上述属性,我们将使用 Length 方法和字符串的 if/else 条件来编写命令。例如,
Function ValidateStorageName { param ( [String]$StorageName ) if(($StorageName.Length -gt 3) -and ($StorageName.Length -lt 15)) { Write-Output "`nStorage Name validated" } else { Write-Output "`nStorage Name validation failed" } }
输出−
PS C:\> ValidateStorageName -StorageName Alpha Storage Name validated PS C:\> ValidateStorageName -StorageName CN Storage Name validation failed
如果条件不满足,则使用ValidateLength 属性后,else 条件将自行起作用。
Function ValidateStorageName { param ( [ValidateLength(3,15)] [String]$StorageName ) Write-Output "Storage Name validated" }
输出−
PS C:\> ValidateStorageName -StorageName Alpha Storage Name validated PS C:\> ValidateStorageName -StorageName CN ValidateStorageName: Cannot validate argument on parameter 'StorageName'. The cha racter length (2) of the argument is too short. Specify an argument with a length that is greater than or equal to "3", and then try the command again
广告