Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

PowerShell Scripting with [ValidatePattern]

Posted on April 19, 2012

I've been writing about a number of parameters attributes you can include in your PowerShell scripting to validate parameter values. Today I want to cover using a regular expression pattern to validate a parameter value. I'm going to assume you have a rudimentary knowledge of how to use regular expressions in PowerShell. If not, there is an entire chapter devoted to the topic in Windows PowerShell 2.0: TFM.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

The parameter attribute is [ValidatePattern()]. Inside the parentheses you place a scriptblock with the regular expression pattern. For example, in PowerShell we might write a command like this to verify if something is a number of 1 to 3 digits.:


$x -match "^\d{1,3}$"

To use that pattern in a [ValidatePattern()] attribute, you would write it like this:


[ValidatePattern({^\d{1,3}$})]

There is no need to use the -match operator or $_. Sure, I suppose you could write a validation script to achieve the same effect, but this is just as easy. I recommend testing your pattern from the PowerShell prompt, especially testing for failures. Here's a more complete example.

Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a UNC path like \\server\share")]
[ValidatePattern({^\\\\\S*\\\S*$})]
[ValidateScript({Test-Path -Path $_ })]
[string]$Path
)

Write-Host "Getting top level folder size for $Path" -ForegroundColor Magenta
dir $path | measure-object -Property Length -sum

For you regular expression gurus, don't get hung up on my pattern. It works for my purposes of illustration. Your pattern can be as simple or as complex as you need it to be. In this short script I'm expecting a path value like \\file01\public. If the value is not in this format, the pattern validation will fail, PowerShell will throw an exception and the script will fail.

Notice I'm also using a second parameter validation attribute, [ValidateScript()]. It is possible for the pattern to be correct but invalid so I can combine both validation tests.


PS C:\> S:\Demo-ValidatePattern.ps1 '\\file01\temp'
C:\scripts\Demo-ValidatePattern.ps1 : Cannot validate argument on parameter 'Pa
th'. The "Test-Path -Path $_ " validation script for the argument with value "\
\file01\temp" did not return true. Determine why the validation script failed a
nd then try the command again.
At line:1 char:28
+ S:\Demo-ValidatePattern.ps1 <<<< '\\file01\temp' + CategoryInfo : InvalidData: (:) [Demo-ValidatePattern.ps1], Par ameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Demo-ValidatePa ttern.ps1

If you'd like to try out my sample script, you can download it here.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

3 thoughts on “PowerShell Scripting with [ValidatePattern]”

  1. walid toumi says:
    April 19, 2012 at 10:51 am

    hi

    I think you can also use RegexOptions:


    [enum]::GetNames([Text.RegularExpressions.RegexOptions])


    Inside the parentheses you place a scriptblock with the regular expression pattern

    you can also use You can also use quotes:


    PS> gc function:foo

    function foo {
    Param (
    [ValidatePattern('(?i)^(powershell)\1')]
    $test
    )
    echo $test
    }

    PS> foo ('PoWerSHell'*2)

    1. Jeffery Hicks says:
      April 19, 2012 at 10:56 am

      You should be able to use any pattern that would use with -match. If it works there, it should work here.

  2. Pingback: Parameter validation « Mario's Blog

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d