Simplifying Parameter Validation in PowerShell with Private Functions

In my previous blog article, I described how to move code from ValidateScript to a private function for parameter validation in PowerShell. This all came about from a question I received in one of my sessions at the PowerShell + DevOps Global Summit a couple of weeks ago. I enjoy following up with attendees of my presentations when they have questions so I sent a message and a link to my previous blog article to the person who asked if that was possible.

They responded by asking if it was possible to move the custom message that Throw returns to the private function. At first, I didn’t think this would be possible, but decided to try the code to make an accurate determination instead of just assuming it wasn’t possible.

I’ve now learned something else which makes the whole process of moving the validation from the ValidateScript block to a private function much more user friendly which is what I think the person who asked the question was trying to accomplish.

The code within ValidateScript becomes so much simpler.

This is why you want to attend conferences in person and talk with others while you’re there. Communicating with others will make you consider things that you didn’t think were possible and the end result is that you’re writing better and more understandable code.

I’ve also created a companion video for this blog article to show what I’m talking about.

I’d love to hear your thoughts on this topic. Please post them as a comment to this blog article. Also, let me know what you think about having short companion videos to accompany my blog articles.

µ

3 Comments

  1. jkavanagh58

    Thanks for this. I use the validatescript quite a bit and this might help to clean up those instances

    Reply
  2. jaykul

    I don’t like the idea that you have a Test-Noun function that throws 😉

    I also think you’re better off customizing the error message for this specific parameter.

    What if you name your private function `ValidateFileName`, and have it take the ErrorMessage as a parameter? That would make it similar to how the ValidatePattern attribute works in PS6. You’d call it like:

    [ValidateScript({ValidateFileName -ErrorMessage “$_ is not a valid file name”})]

    Reply

Leave a Reply

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

%d bloggers like this: