Parameter validation restricts and checks values supplied to PowerShell functions before automation acts on them. It keeps routine scripts simple while preventing avoidable mistakes, such as entering a positive retention period when the cleanup calculation expects a past date. section 2.1
Validation also protects data quality when a function inserts records into SQL. Mandatory parameters require supplied values, ValidateScript checks conditions such as string length, and ValidateSet limits parameters to approved values. section 7.3.1
Choose the simplest validation that matches the failure you need to prevent:
- Use the Mandatory parameter attribute when a function must receive a value. section 7.3.1
- Use ValidateScript for conditions such as maximum string length; the script block is valid when it returns true. section 7.3.1
- Use ValidateSet for predefined values, preventing misspellings and inconsistent abbreviations in stored data. section 7.3.1
- Prefer a short, less error-prone rule first, then increase complexity if operational mistakes continue. section 2.1
Function New-PoshServer {
param(
[Parameter(Mandatory=$true)]
[ValidateScript({$_.Length -le 50 })]
[string]$Name
)
$PSBoundParameters
}
New-PoshServer -Name 'Srv01'
New-PoshServer -Name 'ThisIsAReallyLongServerNameThatWillCertainlyExceed50Characters'
A reusable function demonstrates Mandatory and ValidateScript together to reject names longer than the permitted database column length. section 7.3.1
[Parameter(Mandatory=$true)]
[ValidateSet('Active','Depot','Retired')]
[string]$Status,
[Parameter(Mandatory=$true)]
[ValidateSet('Windows','Linux')]
[string]$OSType,
[Parameter(Mandatory=$true)]
[ValidateSet('WSMan','SSH','PowerCLI','HyperV','AzureRemote')]
[string]$RemoteMethod,
[Parameter(Mandatory=$true)]
[ValidateSet('Physical','VMware','Hyper-V','Azure','AWS')]
[string]$Source,
A parameter declaration demonstrates ValidateSet for status, operating system, remote method, and source values. section 7.3.1
File cleanup retention period
Let an operator enter a positive number of days, validate that it falls within the accepted range, and convert it to the negative value needed to identify files in the past. This avoids archiving files thirty days too early because of a sign error. section 2.1
