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
