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.

function Test-FileName {
param (
[string]$FileName
)

If ($FileName -match '^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$') {
$True
}
else {
Throw "$_ is either not a valid filename or it is not recommended."
}
}

The code within ValidateScript becomes so much simpler.

function New-MrFile {
[CmdletBinding()]
param (
[ValidateScript({
Test-FileName -FileName $_
})]
[string]$FileName
)
Write-Output $FileName
}

improve-private-param-validation1a.jpg

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.

µ