liveBook · Manning

ValidateScript attribute

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

The ValidateScript attribute validates a PowerShell parameter by evaluating a script block against its supplied value.

The ValidateScript attribute validates a PowerShell parameter by running a script block against its supplied value. A value is accepted only when the script block returns $true, making it useful for enforcing constraints before automation continues. section 7.3.1

For database-oriented functions, use it to protect table inserts from strings that exceed column limits. Combine it with Mandatory when null or blank values must also be rejected. section 7.3.1

Apply the attribute when:

  • A parameter needs a rule expressed as a conditional test, such as limiting a name to 50 characters. section 7.3.1
  • A parameter accepts a fixed vocabulary, prefer ValidateSet for explicit allowed values such as operating systems or statuses. section 7.3.1
  • A parameter is being renamed, combine an alias with a validation script that warns users while returning $true so execution continues. section 14.3.1

Validate a server name

A reusable function can reject an overlong server name before the function body runs: [ValidateScript({$_.Length -le 50})] [string]$Name. A valid value such as 'Srv01' proceeds; a longer value fails parameter validation. section 7.3.1

param(
    [Alias('Name')]
    [ValidateScript({
        Write-Warning "The parameter Name is being replaced with HostName. Be sure to update any scripts using Name";
        $true}
    )]
    [string]$HostName
)

Use the complete listing to stage a parameter rename: retain Name as an alias, warn when it is used, and return $true from the validation script. section 14.3.1

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Defines the true-return rule and demonstrates length checks, warning behavior, and the complementary ValidateSet pattern.
Examples
Uses a 50-character server name check, fixed infrastructure-value sets, and a Name-to-HostName migration warning.
What it assumes
Assumes familiarity with PowerShell functions and parameters while teaching the true-return contract from the validation examples.
What you can do after
Builds PowerShell parameters that reject invalid values or warn about renamed parameters while preserving execution.
How it connects
Connects parameter validation with Mandatory, ValidateSet, aliases, deprecation warnings, and SQL data constraints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.