Limiting Variables to a certain Length

by Feb 2, 2009

With strong typing, you can limit a variable to only a certain data type such as String:

[String]$a = 'Hello'

By adding a ValidateLengthAttribute, you can further limit the variable to only text of certain length. The following code limits the variable a to text which is between 2 and 8 characters long:

(Get-Variable a).Attributes.Add($(New-Object `
System.Management.Automation.ValidateLengthAttribute `
-ArgumentList 2,8))

Now, assigning text which is shorter or longer than the limit will raise an exception:

$a = "Longer than 8 characters"