Steven Murawski

SysAdmin, DevOps, PowerShell, and Other Stuff

Parameter Validation

Glenn Sizemore wrote a great Scripting Games wrap up post about some of the parameter validation options that are available.  Go read it, I'll wait.

The Smackdown - Ensuring You Have A Value

Very often you need to make sure that a parameter will not have a null value.  There are a couple of options in making sure you have valid content.

ValidateNotNull vs. ValidateNotNullOrEmpty

When you start to look at some of the validation parameters (in about_Advanced_Functions), the two that leap out are the ValidateNotNull and ValidateNotNullOrEmpty. 

Just looking at that names hints that there is something different about them, but it might not be immediately obvious.

ValidateNotNull will check if a parameter value is null when it is assigned.  If it has a null value, the runtime will throw an error.

ValidateNotNullOrEmpty has some additional checks to help with arrays and strings.  For example, if my function takes a parameter called ComputerName (like

param(  [parameter()]
  [string[]]
  $ComputerName
)

and I apply the ValidateNotNull parameter,

param(
  [parameter()]
  [string[]]
  [ValidateNotNull]
  $ComputerName
)

I will only get an error if I pass $null

c:\scripts\MyScript.ps1 -ComputerName $null

MyScript.ps1 : Cannot validate argument on parameter 'ComputerName'. The argument is null. Supply a non-null argument and try the command again.

But, if I pass an empty array, or an empty string, the command will accept the input.

c:\scripts\MyScript.ps1 -ComputerName ""
c:\scripts\MyScript.ps1 -ComputerName @()

To use validation to protect against those types of input, I can use ValidateNotNullOrEmpty

param(
  [parameter()]
  [string[]]
  [ValidateNotNullOrEmpty]
  $ComputerName
)

Then I will receive an error like this.

MyScript.ps1 : Cannot validate argument on parameter 'test'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again.

ValidateNotNull(OrEmpty) vs. Mandatory

Neither ValidateNotNull nor ValidateNotNullOrEmpty force a parameter to be declared.  The validations only have an impact if values (or lack thereof) are actually declared or passed in via the pipeline.  If you would like to make a parameter required, you can set the Mandatory flag in the Parameter attribute.

param(
  [parameter(Mandatory=$true)]
  [string[]]
  $ComputerName
)

This will make the parameter required and does protect against both empty strings and empty arrays, so you will not need to use either of those validation attributes. 

NOTE: Other validations can still be done (like ValidateSet, ValidateRange, and ValidateScript).