Power Shell Function Validate Object Properties Using ValidateScript

 

Recently I was working on a Power Shell script with many custom functions. When I started to use Power Shell custom objects I wanted to be able to pass them to a function. So I faced the challenge of validating my object for all required properties and came up with this solution, using the ValidateScript block to test the object:

Customizing the ValidateScript

As you can see I use a ValidateScript for the parameter validation to test the object for the required properties. The properties can be specified in an array:

When we call the Function with an appropriate object:

We get the following output:

Result

If we remove one or more properties from our custom object, an error is thrown:

If you want to go a step further you could extend the ValidateScript to...

Prevent passing properties with a NULL or empty value

If we call our function again with the added IsNullOrEmpty validation NULL or emtpy values throw an exception:

Final Result

Last but not least, here's the full function with an example object:

If you have any questions or improvements just let me know.

Happy ValidateScripting!

How to manage Printers with Power Shell.

Reference:

 

Nicola

The guy behind this blog. Combining work sports and social life.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

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