- Courses
- đź’»Programming Languages
- 🪟PowerShell
- PowerShell Scripting at Scale
- Writing Professional Scripts
- Input Validation
On this page
PowerShell Input Validation Guide
Updated on June 22, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Input validation is one of the most important pillars of professional PowerShell scripting. A script that accepts user input—parameters, file paths, credentials, or data from external systems—must verify that the input is correct, safe, and usable before performing any actions. Without validation, scripts become fragile, unpredictable, and potentially dangerous. PowerShell provides a rich set of built-in validation attributes such as ValidateNotNullOrEmpty, ValidateSet, ValidateRange, ValidatePattern, and ValidateScript that enforce rules at the point of entry. For complex validation, manual checks with Test-Path, Get-Module, and permissions verification ensure the execution environment is ready. Clear, actionable error messages and a "fail fast" approach prevent cascading failures. By combining these techniques, you create scripts that are safe, predictable, and maintainable.
Why Input Validation Matters​
Professional scripts must assume that input may be:
- Missing
- Incorrect
- Malformed
- Unexpected
- Unsafe
Good validation ensures:
- Reliability — the script behaves predictably
- Safety — invalid input does not cause destructive actions
- Clarity — users receive meaningful error messages
- Maintainability — future administrators understand constraints
- Security — malicious or accidental misuse is prevented
A script that validates input early avoids cascading failures later.
PowerShell's Built-In Validation Attributes​
PowerShell provides a rich set of validation attributes that can be applied directly to parameters. These attributes enforce rules before the script runs any logic.
Common validation attributes include:
AttributePurpose[ValidateNotNull()]Value cannot be $null``[ValidateNotNullOrEmpty()]Value cannot be $null or empty[ValidateSet()]Restricts input to specific values[ValidateRange()]Enforces numeric boundaries[ValidatePattern()]Enforces regex patterns[ValidateScript()]Custom validation logic[ValidateCount()]Enforces array length limits[ValidateLength()]Enforces string length limits[ValidateDrive()]Validates drive existence
These attributes make validation declarative and consistent. When validation fails, PowerShell automatically generates an error message without requiring additional code.
Examples of Parameter Validation​
Ensuring a Required String Is Not Empty​
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
Code explanation: [Parameter(Mandatory)] makes the parameter required. [ValidateNotNullOrEmpty()] ensures the user provides a value that is not $null or an empty string. This prevents the script from running unless a valid username is provided.
Restricting Input to a Predefined Set​
param(
[ValidateSet("Low", "Medium", "High")]
[string]$Priority = "Medium"
)
Code explanation: [ValidateSet()] restricts the parameter to one of the specified values. The script will fail with a clear error if an invalid value is provided. The default value "Medium" is used when the parameter is omitted.
Validating Numeric Ranges​
param(
[ValidateRange(1, 100)]
[int]$RetryCount = 5
)
Code explanation: [ValidateRange()] enforces that the integer value is between 1 and 100 (inclusive). This prevents invalid or dangerous values from being used, such as a retry count of zero or a negative number.
Validating with a Regular Expression​
param(
[ValidatePattern("^[a-z0-9._%-]+@contoso\.com$")]
[string]$Email
)
Code explanation: [ValidatePattern()] uses a regular expression to ensure the email address matches the expected domain format. This prevents typographical errors and ensures only contoso.com addresses are accepted.
Using Custom Validation Logic​
ValidateScript allows you to write arbitrary validation code. The script block must return $true for validation to succeed:
param(
[ValidateScript({ Test-Path $_ })]
[string]$Path
)
Code explanation: The ValidateScript block receives the parameter value as $_. Test-Path $_ returns $true if the path exists. If the path does not exist, validation fails and PowerShell generates an error. This ensures the provided path exists before the script runs.
Validating Array Length​
param(
[ValidateCount(1, 10)]
[string[]]$ComputerNames
)
Code explanation: [ValidateCount()] ensures the array contains between 1 and 10 elements. This prevents the script from running with no targets or an excessive number of targets.
Validating String Length​
param(
[ValidateLength(3, 20)]
[string]$Name
)
Code explanation: [ValidateLength()] ensures the string is between 3 and 20 characters long. This is useful for enforcing naming conventions.
Manual Validation Inside the Script​
Not all validation can be expressed through attributes. Sometimes you need more complex logic.
Validating CSV File Structure​
$requiredColumns = "Name", "SamAccountName", "Password"
$csv = Import-Csv $Path
foreach ($col in $requiredColumns) {
if (-not ($csv | Get-Member -Name $col)) {
throw "The CSV file is missing the required column: $col"
}
}
Code explanation: After importing the CSV, the script checks whether each required column exists. Get-Member -Name $col returns $true if the column exists in the CSV object. If any column is missing, the script throws an error, preventing execution with incomplete data.
Validating Values in a CSV​
$csv = Import-Csv $Path
foreach ($row in $csv) {
if ([string]::IsNullOrWhiteSpace($row.SamAccountName)) {
throw "SamAccountName cannot be empty in row: $($row | ConvertTo-Json)"
}
}
Code explanation: Each row is validated individually. [string]::IsNullOrWhiteSpace() checks for empty or whitespace-only values. This ensures data quality before any AD operations are performed.
Validating Using Try/Catch​
try {
$user = Get-ADUser -Identity $Username -ErrorAction Stop
}
catch {
throw "User '$Username' does not exist in Active Directory."
}
Code explanation: The try block attempts to retrieve the user. -ErrorAction Stop converts non-terminating errors to terminating errors, which are caught by the catch block. This provides a clear, actionable error message rather than a raw AD error.
Validating External Dependencies​
Professional scripts also validate the execution environment.
Validating Modules​
if (-not (Get-Module -ListAvailable ActiveDirectory)) {
throw "ActiveDirectory module is required but not installed."
}
Import-Module ActiveDirectory -ErrorAction Stop
Code explanation: Get-Module -ListAvailable checks if the module is installed. If not, the script throws an error. If installed, Import-Module loads it with -ErrorAction Stop to catch any loading errors.
Validating Permissions​
# Check for administrative privileges
if (-not ([Security.Principal.WindowsPrincipal]::new(
[Security.Principal.WindowsIdentity]::GetCurrent()
)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "This script must be run as Administrator."
}
Code explanation: This uses the .NET WindowsPrincipal class to check whether the current user is in the Administrator role. The IsInRole method returns $true if the user is an administrator, allowing the script to continue or fail accordingly.
Validating Network Connectivity​
if (-not (Test-Connection -ComputerName $Server -Count 1 -Quiet)) {
throw "Cannot reach server: $Server"
}
Code explanation: Test-Connection -Count 1 -Quiet sends a single ICMP ping and returns $true if the server responds. If the server is unreachable, the script throws an error before attempting any operations.
Validating Required Environment Variables​
$requiredVars = @("API_KEY", "API_URL")
foreach ($var in $requiredVars) {
if (-not (Test-Path "env:$var")) {
throw "Required environment variable '$var' is not set."
}
}
Code explanation: Test-Path "env:$var" checks whether the environment variable exists. This is essential for scripts that rely on external configuration.
Providing Helpful Error Messages​
Validation errors should be clear, specific, and actionable.
Bad Example​
Error: Invalid input.
Code explanation: This message does not explain what is wrong or how to fix it. It leaves the user guessing.
Good Example​
The value 'abc' is not valid for parameter RetryCount. Expected a number between 1 and 100.
Code explanation: This message identifies the parameter, the invalid value, and the expected range. The user immediately knows what to correct.
Error Message Template​
When writing custom error messages, follow this structure:
throw "Parameter 'ParamName': Value '$value' is invalid. Expected: $expected."
Code explanation: Include the parameter name, the invalid value, and the expected format. This consistency makes error messages easier to understand and debug.
Failing Fast​
A professional script should stop immediately when validation fails.
This prevents:
- Partial execution
- Inconsistent state
- Corrupted data
- Unpredictable behavior
Example​
if (-not (Test-Path $Path)) {
throw "Input file not found: $Path"
}
Code explanation: The script checks for the file's existence and immediately throws an error if it is missing. No further code is executed, preventing any operations on a missing file.
Using exit for Non-Terminating Failures​
In scripts that are not functions, throw is not always appropriate. Use exit to stop execution:
if (-not (Get-Module -ListAvailable ActiveDirectory)) {
Write-Error "ActiveDirectory module is required."
exit 1
}
Code explanation: Write-Error displays the error message, and exit 1 terminates the script with a non-zero exit code, indicating failure.
Combining Validation with Logging​
Validation and logging work together to provide a complete audit trail:
if (-not (Test-Path $Path)) {
Write-Log -Message "Input file missing: $Path" -Level "ERROR"
throw "Input file not found."
}
Code explanation: The script logs the validation failure before throwing the error. This ensures that validation failures are recorded for auditing and troubleshooting, even if the script terminates.
Practical Example: A Script with Strong Validation​
<#
.SYNOPSIS
Creates AD user accounts from a CSV file with robust validation.
.DESCRIPTION
Imports user data from a CSV, validates all inputs, and creates AD accounts.
.PARAMETER Path
Path to the CSV file containing user data. Must exist.
.PARAMETER Priority
Priority level for the operation. Valid values: Low, Medium, High.
.PARAMETER LogPath
Optional path for logging. If provided, the directory must exist.
#>
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $_ -PathType Leaf })]
[string]$Path,
[ValidateSet("Low", "Medium", "High")]
[string]$Priority = "Medium",
[ValidateScript({ Test-Path (Split-Path $_) -PathType Container })]
[string]$LogPath
)
# Validate module dependency
if (-not (Get-Module -ListAvailable ActiveDirectory)) {
throw "ActiveDirectory module is required but not installed."
}
Import-Module ActiveDirectory -ErrorAction Stop
# Validate CSV structure
$csv = Import-Csv $Path -ErrorAction Stop
$requiredColumns = "Name", "SamAccountName", "Password"
foreach ($col in $requiredColumns) {
if (-not ($csv | Get-Member -Name $col)) {
throw "The CSV file is missing the required column: $col"
}
}
# Validate CSV data
foreach ($row in $csv) {
if ([string]::IsNullOrWhiteSpace($row.SamAccountName)) {
throw "SamAccountName cannot be empty in row: $($row | ConvertTo-Json)"
}
}
# Main execution logic
Write-Output "Processing $($csv.Count) users with Priority: $Priority"
# ... user creation logic ...
Code explanation: This script demonstrates comprehensive validation:
- Parameters are validated with attributes:
ValidateNotNullOrEmpty,ValidateSet, andValidateScript. - Environment validation ensures the ActiveDirectory module is installed and loaded.
- CSV structure validation ensures all required columns exist.
- CSV data validation ensures values are not empty.
- The
$Priorityparameter provides a default value, making the parameter optional while still controlling behavior.
Summary​
Input validation is a core component of professional PowerShell scripting. It ensures that your scripts are:
- Safe — invalid input does not cause destructive actions
- Predictable — the script behaves consistently
- Maintainable — future administrators understand constraints
- User-friendly — error messages are clear and actionable
- Resistant — to invalid or malicious input
By using PowerShell's built-in validation attributes (ValidateNotNullOrEmpty, ValidateSet, ValidateRange, ValidatePattern, ValidateScript), performing manual checks for complex logic, validating the environment (modules, permissions, connectivity), and providing clear error messages, you create scripts that behave reliably and inspire confidence in anyone who uses them.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Logging Strategies
Next
Modules & Packaging
-
Why Input Validation Matters
-
PowerShell's Built-In Validation Attributes
-
Examples of Parameter Validation
- Ensuring a Required String Is Not Empty
- Restricting Input to a Predefined Set
- Validating Numeric Ranges
- Validating with a Regular Expression
- Using Custom Validation Logic
- Validating Array Length
- Validating String Length
-
Manual Validation Inside the Script
- Validating CSV File Structure
- Validating Values in a CSV
- Validating Using Try/Catch
-
Validating External Dependencies
- Validating Modules
- Validating Permissions
- Validating Network Connectivity
- Validating Required Environment Variables
-
Providing Helpful Error Messages
- Bad Example
- Good Example
- Error Message Template
-
Failing Fast
- Example
- Using
exitfor Non-Terminating Failures
-
Combining Validation with Logging
-
Practical Example: A Script with Strong Validation
-
Summary
