PowerShell Parameter Validation Attributes

 
 
  • Gérald Barré

PowerShell provides a set of validation attributes that enforce constraints on parameters and variables. These attributes validate input at runtime, making your scripts more robust and reducing the need for manual validation logic.

#Overview

Validation attributes can be applied to:

  • Function or script parameters
  • Script-level variables
  • Class properties

When validation fails, PowerShell throws an exception with a descriptive error message, preventing invalid values from being used.

#ValidateScript

The ValidateScript attribute lets you define custom validation logic using a script block. The $_ variable represents the value being validated.

PowerShell
function Test-EvenNumber {
    param(
        [ValidateScript({ $_ % 2 -eq 0 })]
        [int]$Number
    )
    Write-Host "Valid even number: $Number"
}

Test-EvenNumber -Number 4  # Works
Test-EvenNumber -Number 5  # Throws error

You can also apply it to variables:

PowerShell
[ValidateScript({ $_ % 2 -ne 0 })] $oddNumber = 3
$oddNumber = 5  # Works
$oddNumber = 4  # Throws error

For better error messages in PowerShell 6.0+, use the ErrorMessage parameter. The {0} placeholder represents the actual value that failed validation:

PowerShell
function Set-EventDate {
    param(
        [ValidateScript(
            { $_ -ge (Get-Date) },
            ErrorMessage = "{0} isn't a future date. Specify a later date."
        )]
        [datetime]$EventDate
    )
    Write-Host "Event scheduled for $EventDate"
}

In earlier PowerShell versions, you can throw a custom exception:

PowerShell
[ValidateScript({
    if ($_ % 2 -eq 0) { return $true }
    throw "Value $_ must be an even number"
})]
[int]$Number

#ValidateRange

The ValidateRange attribute ensures a numeric value falls within a specified range.

PowerShell
function Set-Volume {
    param(
        [ValidateRange(0, 100)]
        [int]$Level
    )
    Write-Host "Setting volume to $Level%"
}

Set-Volume -Level 50   # Works
Set-Volume -Level 150  # Throws error

#ValidateSet

The ValidateSet attribute restricts values to a predefined set of options. This provides tab completion in the console.

PowerShell
function Get-EnvironmentInfo {
    param(
        [ValidateSet('Development', 'Staging', 'Production')]
        [string]$Environment
    )
    Write-Host "Getting info for $Environment"
}

Get-EnvironmentInfo -Environment 'Production'  # Works
Get-EnvironmentInfo -Environment 'Test'        # Throws error

#ValidatePattern

The ValidatePattern attribute validates values against a regular expression.

PowerShell
function Send-Email {
    param(
        [ValidatePattern('^[\w\.-]+@[\w\.-]+\.\w+$')]
        [string]$EmailAddress
    )
    Write-Host "Sending email to $EmailAddress"
}

Send-Email -EmailAddress 'user@example.com'  # Works
Send-Email -EmailAddress 'invalid-email'     # Throws error

#ValidateLength

The ValidateLength attribute ensures a string's length falls within a specified range.

PowerShell
function New-Password {
    param(
        [ValidateLength(8, 20)]
        [string]$Password
    )
    Write-Host "Password length is valid"
}

New-Password -Password 'MyP@ssw0rd'  # Works
New-Password -Password 'short'       # Throws error

#ValidateCount

The ValidateCount attribute validates the number of elements in an array or collection.

PowerShell
function Add-Users {
    param(
        [ValidateCount(1, 5)]
        [string[]]$UserNames
    )
    Write-Host "Adding $($UserNames.Count) users"
}

Add-Users -UserNames 'Alice', 'Bob'              # Works
Add-Users -UserNames @()                         # Throws error (min 1)
Add-Users -UserNames 1..10 | ForEach-Object {"User$_"}  # Throws error (max 5)

#ValidateNotNull

The ValidateNotNull attribute ensures a parameter is not null.

PowerShell
function Process-Data {
    param(
        [ValidateNotNull()]
        [object]$Data
    )
    Write-Host "Processing data: $Data"
}

Process-Data -Data 'some data'  # Works
Process-Data -Data $null        # Throws error

#ValidateNotNullOrEmpty

The ValidateNotNullOrEmpty attribute ensures a string or collection is not null or empty.

PowerShell
function Write-Log {
    param(
        [ValidateNotNullOrEmpty()]
        [string]$Message
    )
    Write-Host "Log: $Message"
}

Write-Log -Message 'Important event'  # Works
Write-Log -Message ''                 # Throws error
Write-Log -Message $null              # Throws error

This also works with arrays:

PowerShell
function Process-Items {
    param(
        [ValidateNotNullOrEmpty()]
        [string[]]$Items
    )
    Write-Host "Processing $($Items.Count) items"
}

Process-Items -Items 'Item1', 'Item2'  # Works
Process-Items -Items @()               # Throws error

#ValidateNotNullOrWhiteSpace

Available in PowerShell 6.0+, the ValidateNotNullOrWhiteSpace attribute ensures a string is not null, empty, or whitespace-only.

PowerShell
function New-Document {
    param(
        [ValidateNotNullOrWhiteSpace()]
        [string]$Title
    )
    Write-Host "Creating document: $Title"
}

New-Document -Title 'My Document'  # Works
New-Document -Title '   '          # Throws error

#ValidateDrive

The ValidateDrive attribute validates that a path uses one of the specified PowerShell drives.

PowerShell
function Get-FileInfo {
    param(
        [ValidateDrive('C', 'D', 'Temp')]
        [string]$Path
    )
    Write-Host "Getting info for: $Path"
}

Get-FileInfo -Path 'C:\Windows\System32'  # Works
Get-FileInfo -Path 'Temp:\file.txt'       # Works (if Temp: drive exists)
Get-FileInfo -Path 'Z:\file.txt'          # Throws error

#ValidateUserDrive

The ValidateUserDrive attribute ensures a path uses a user-created PowerShell drive (not built-in drives like C:, D:, etc.).

PowerShell
New-PSDrive -Name 'MyDrive' -PSProvider FileSystem -Root 'C:\MyFolder'

function Read-UserFile {
    param(
        [ValidateDrive()]
        [ValidateUserDrive()]
        [string]$Path
    )
    Get-Content -Path $Path
}

Read-UserFile -Path 'MyDrive:\file.txt'  # Works
Read-UserFile -Path 'C:\file.txt'        # Throws error

#ValidateTrustedData

Available in PowerShell 6.1.1+, the ValidateTrustedData attribute ensures data comes from a trusted source, preventing untrusted data injection.

PowerShell
function Invoke-TrustedCommand {
    param(
        [ValidateTrustedData()]
        [string]$Command
    )
    Invoke-Expression $Command
}

This is primarily used in security-sensitive scenarios to ensure parameters come from trusted sources rather than user input.

#Combining Multiple Attributes

You can apply multiple validation attributes to a single parameter:

PowerShell
function Set-Configuration {
    param(
        [ValidateNotNullOrEmpty()]
        [ValidateLength(3, 50)]
        [ValidatePattern('^[a-zA-Z0-9_-]+$')]
        [string]$ConfigName
    )
    Write-Host "Setting configuration: $ConfigName"
}

Set-Configuration -ConfigName 'my-config_123'  # Works
Set-Configuration -ConfigName 'ab'             # Throws error (too short)
Set-Configuration -ConfigName 'invalid@name'   # Throws error (invalid pattern)

All validation attributes are evaluated in the order they appear. If any validation fails, an error is thrown immediately.

#Additional Resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?