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属性,如果条件不满足,则条件本身将起作用。
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