Easy validating parameter input using ValidateCount, ValidateLength, ValidatePattern, ValidateRange, ValidateSet and ValidateScript in PowerShell

Windows PowerShell introduced parameter validation which drastically reduces lines of validation code – and replaces it with a couple of markup tags:

 

ValidateCount (int minLength, int maxlength)
How many arguments are allowed for a parameter.

[ValidateCount(1,3)]
[String[]]
$Collection

ValidateLength (int minLength, int maxlength)

Length (in characters) of a parameter argument.

[ValidateLength(1,8)]
[String[]]
$Phone

ValidatePattern (string regexString, Named Parameters)
Valid patterns for a parameter argument.

[ValidatePattern("[0-9][0-9][0-9][0-9]")]
[String[]]
$Pin

ValidateRange (object minRange, object maxRange)
Valid range for a parameter argument.

[ValidateRange(18,120)]
[Int]
$Number

ValidateSet (string[] validValues, Named Parameters)
Possible values for a parameter argument.

[ValidateSet("One","Two","Three","Four")]
[String]
$TextString

ValidateScript (scriptblock validValues)
Custom script for validation

[ValidateScript({Test-Path $_ -PathType 'Container'})]
[String]
$Path

ValidateNotNull ()
Input is not null

[ValidateNotNull()]
[String]
$Id

ValidateNotNullOrEmpty ()
Input is neither null or empty

[ValidateNotNullOrEmpty()]
[String[]]
$UserName

 

Read more about validating parameters on MSDN:

Or use PowerShell built-in help:

 

Published by

Henrik Damgaard

Hi I’m Henrik and I write this blog based on useful topics I find interesting – mostly covering some of my technical interests : System Center Operations Manager (SCOM), BizTalk, Windows Server, PowerShell, SQL server, Internet Information Services, PHP and .NET I am currently holding a position as System Administrator with focus on Microsoft server products.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.