How to use the ValidateLength attribute in PowerShell?
https://www.tutorialspoint.com/how-to-use-the-validatelength-attribute-in-powershell
-
20-09-2020 - |
Pregunta
How to use the ValidateLength attribute in PowerShell?
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
Advertisements
No afiliado a Tutorialspoint