PowerShell Core 6: ValidatePattern Custom Error Messages

Last week, I received a comment on my previous blog article from fellow Microsoft MVP Joel Bennett which referenced using an ErrorMessage parameter similar to how ValidatePattern works in PowerShell Core version 6. I knew I'd seen some discussion about this on GitHub, but I wasn't aware that it had made it into the production release. Joel's message is shown in the following image.


validation-customerror1a.jpg


I had to figure out how to use custom error messages with ValidatePattern. After all, that was the whole reason I avoided using ValidatePattern in the first place and wrote my own better ValidatePattern using ValidateScript. Taking a look at the about_Functions_Advanced_Parameters help topic and searching around on the Internet revealed nothing at all. Since I knew I had previously seen something about it on GitHub, I headed over there for answers. Bingo! Issue 3748 in the PowerShell repository revealed what I was looking for. Not only had custom error message support been added to ValidatePattern, but it had also been added to ValidateScript and ValidateSet.

The following code shows a simple example of using a custom error message with the ValidatePattern parameter validation attribute in PowerShell Core 6.

1function Test-ValidatePattern {
2    [CmdletBinding()]
3    param (
4        [ValidatePattern('^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$',
5                         ErrorMessage = "{0} is not a valid file name")]
6        [string]$FileName
7    )
8    Write-Output $FileName
9}

validation-customerror2a.jpg

A custom error message can also be used with ValidateScript and ValidateSet just like with what's shown in the previous example, except using those parameter validation attributes instead of ValidatePattern. Keep in mind, this only works with PowerShell Core and not Windows PowerShell.

µ