# How to use the ValidateLength attribute in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

The ValidateLength attribute in PowerShell is used to validate the length of the String. Generally how we write the command without the mentioned attribute is using the Length method and if/else condition for the string. For Example,

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" } } ## Output− PS C:\> ValidateStorageName -StorageName Alpha Storage Name validated PS C:\> ValidateStorageName -StorageName CN Storage Name validation failed With the ValidateLength attribute, else condition will work itself if the condition doesn’t satisfy. Function ValidateStorageName { param ( [ValidateLength(3,15)] [String]$StorageName
)
Write-Output "Storage Name validated"
}

## Output−

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
Updated on 19-Sep-2020 09:06:20