Parameter validation helps check if the inputs to a script or function are correct before running it. This stops errors early and makes scripts safer.
0
0
Parameter validation in PowerShell
Introduction
When you want to make sure a user enters a number within a certain range.
When a script needs a file path and you want to check if the file exists.
When you want to allow only specific choices for a parameter.
When you want to ensure a parameter is not empty or null.
When you want to avoid running a script with wrong or missing inputs.
Syntax
PowerShell
function My-Function { param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [ValidateRange(1, 10)] [int]$Count ) # Function code here }
Use [Parameter(Mandatory=$true)] to require a parameter.
Validation attributes like [ValidateRange] or [ValidateNotNullOrEmpty] check input before the script runs.
Examples
This function only accepts ages between 0 and 120.
PowerShell
function Get-UserAge { param( [ValidateRange(0, 120)] [int]$Age ) "User age is $Age" }
This checks if the file path exists before continuing.
PowerShell
function Set-FilePath { param( [ValidateScript({Test-Path $_})] [string]$Path ) "File path is valid: $Path" }
This only allows the colors Red, Green, or Blue as input.
PowerShell
function Choose-Color { param( [ValidateSet('Red', 'Green', 'Blue')] [string]$Color ) "You chose $Color" }
Sample Program
This script greets a person by name a certain number of times. It checks that the name is not empty and the number of times is between 1 and 5.
PowerShell
function Greet-Person { param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [ValidateRange(1, 5)] [int]$Times = 1 ) for ($i = 1; $i -le $Times; $i++) { Write-Output "Hello, $Name!" } } # Call the function Greet-Person -Name "Alice" -Times 3
OutputSuccess
Important Notes
If validation fails, PowerShell shows an error and stops the script.
You can combine multiple validation attributes for stronger checks.
Default values can be set for parameters to make them optional.
Summary
Parameter validation checks inputs before running code.
Use attributes like [ValidateRange], [ValidateSet], and [ValidateNotNullOrEmpty].
Validation helps avoid errors and makes scripts safer and easier to use.