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: