Function parameter validation–NotNullorEmpty

A question on the forum made me realise that there is still  a lot of confusion around the advanced function parameter validation options so I thought I’d spend  a few posts clearing some of the confusion.

The question was about ValidateNotNullorEmpty so I’ll start with that one.

function test {
param (



If you supply a path – it’s echoed back to you:

£> test -Path C:\Test

If you don’t supply the path parameter you’ll be prompted for it:

£> test
cmdlet test at command pipeline position 1
Supply values for the following parameters:
Path: c:\test

if you use the function and don’t supply a value:

£> test -Path
test : Missing an argument for parameter ‘Path’. Specify a parameter of type ‘System.String’ and try again.
At line:1 char:6
+ test -Path
+      ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [test], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,test

The validation routine kicks in.

The pipeline works as well:

£> Get-ChildItem -Path c:\ -Filter test | test

Though notice that its returning Test instead of c:\test – that’s because Get-ChildItem doesn’t return a property called path but Name is the first string property accessible in the object which is why its used.

Now if you try to access a non-existent path in this way

£> Get-ChildItem -Path c:\ -Filter test27 | test


You’ll get nothing returned  – because

Get-ChildItem -Path c:\ -Filter test27

doesn’t put anything on the pipeline so test is never called.

If you want to see the function work with a non-existent folder try this:

£> test -Path (Get-ChildItem -Path c:\ -Filter test27)
test : Cannot validate argument on parameter ‘Path’. The argument is null or empty. Provide an argument that is not null
or empty, and then try the command again.
At line:1 char:12
+ test -Path (Get-ChildItem -Path c:\ -Filter test27)
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test

ValidateNotNullEmpty is a good test for determining if a value is present and not Null or an empty string. It should be paired where possible with mandatory=$true to ensure that the parameter is used.

This and other validation options are discussed in about_Functions_Advanced_Parameters

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s