Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

PowerShell Scripting with [ValidateLength]

Posted on April 20, 2012

In continuing the exploration of parameter validation attributes, today we'll look at [ValidateLength()]. You can use this attribute in your PowerShell scripting to validate that a parameter value is at least a certain length and no more and a certain length. In other words, it has to be just right. Here's what it looks like:

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!


[ValidateLength(2,10)]
[string]$Fooby

In this example any value for -Fooby must be at least 2 characters long and no more than 10. Anything outside of that range and PowerShell will raise an exception. You have to supply both values in the validation attribute. An alternative would be to use [ValidateScript()].


[ValidateScript({ $_.Length -ge 5})]
[string]$Name

Now, any value for -Name must be at least 5 characters and there is no upper limit. Here's a more complete example.


#requires -version 2.0

[cmdletbinding(SupportsShouldProcess=$True)]

Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter name between 5 and 15 characters")]
[ValidateLength(5,15)]
[string]$Name,
[Parameter(Position=1,Mandatory=$True,HelpMessage="Enter password between 7 and 64 characters")]
[ValidateLength(7,64)]
[ValidatePattern({^\S+$})]
[string]$Password,
[string]$Computername=$env:computername,
[switch]$Passthru
)

Write-Host "Creating $name with password of $Password on $computername" -ForegroundColor Green
[ADSI]$Server="WinNT://$computername"
$User=$server.Create("User",$Name)

if ($pscmdlet.ShouldProcess($User.Path)) {
Write-Host "Committing new account changes" -ForegroundColor Green

<# #uncomment the next lines if you really, really want to do this $User.SetInfo() Write-Host "Setting password" -ForegroundColor Green $User.SetPassword($Password) If ($passthru) { Write-Output $User } #>
}

This script will create a local user account. I'm asking that the user name be between 5 and 15 characters and that the password be between 7 and 64 characters. I've also added a second validation check on the password using [ValidatePattern()] to verify it doesn't contain any spaces.

The exception message you see with [ValidateLength()] depends on where you fall short.


PS S:\> .\Demo-ValidateLength.ps1 Jeff Password123
C:\scripts\Demo-ValidateLength.ps1 : Cannot validate argument on parameter 'Nam
e'. The number of characters (4) in the argument is too small. Specify an argum
ent whose length is greater than or equal to "5" and then try the command again
.
At line:1 char:26
+ .\Demo-ValidateLength.ps1 <<<< Jeff Password123 + CategoryInfo : InvalidData: (:) [Demo-ValidateLength.ps1], Para meterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Demo-ValidateLe ngth.ps1 PS S:\> .\Demo-ValidateLength.ps1 JeffJeffJeffJeff Password123
C:\scripts\Demo-ValidateLength.ps1 : Cannot validate argument on parameter 'Nam
e'. The argument length of 16 is too long. Shorten the length of the argument t
o less than or equal to "15" and then try the command again.
At line:1 char:26
+ .\Demo-ValidateLength.ps1 <<<< JeffJeffJeffJeff Password123 + CategoryInfo : InvalidData: (:) [Demo-ValidateLength.ps1], Para meterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Demo-ValidateLe ngth.ps1

If you'd like, you can download Demo-ValidateLength and try it out for yourself.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

5 thoughts on “PowerShell Scripting with [ValidateLength]”

  1. Shay Levy says:
    April 20, 2012 at 2:16 pm

    We can also constrain the input to a specific length by setting the minimum and maximum length to the same value. For instance, this will require a value of exactly three characters:

    [ValidateLength(3,3)]

    1. Jeffery Hicks says:
      April 20, 2012 at 2:17 pm

      I hadn’t thought about that, but absolutely!

  2. Dave in the midwest says:
    April 20, 2012 at 10:56 pm

    Anything coming (in the near future) on regular expressions?
    I can think of a whole lot of uses.

    Btw, did I say Thanks?
    How’s the new MEAP coming?

    1. Jeffery Hicks says:
      April 21, 2012 at 9:56 pm

      Thanks for your comments. A lot of the MEAP is dependent on final and shipping v3 code. I’m not much of a regular expression guy, but certainly something I can cover as far as basics are concerned.

  3. Pingback: Parameter validation « Mario's Blog

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d