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.

 1function Test-FileName {
 2    param (
 3        [string]$FileName
 4    )
 5
 6    If ($FileName -match '^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$') {
 7        $True
 8    }
 9    else {
10        Throw "$_ is either not a valid filename or it is not recommended."
11    }
12}

The code within ValidateScript becomes so much simpler.

 1function New-MrFile {
 2    [CmdletBinding()]
 3    param (
 4        [ValidateScript({
 5                Test-FileName -FileName $_
 6        })]
 7        [string]$FileName
 8    )
 9    Write-Output $FileName
10}

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.

µ