PowerShell Parameters and validation
Reject invalid inputs at the boundary and explain what your function accepts.
Documentation: Microsoft Learn
Overview
The service-report example requires a Name, permits two Status values and limits First to 1 through 100. These rules document the function’s contract and catch invalid arguments during parameter binding.
Mandatory means the caller must supply a value or be prompted where prompting is available. It does not prove that the value identifies a real service. Type constraints and validation attributes cover different checks; environmental checks may still belong in the body.
Use ValidateSet for a small stable set of choices and ValidateRange for numeric limits. For dynamic conditions, such as a path remaining available during a write, an early validation check cannot eliminate the need to handle failure at the operation itself.
In unattended execution, supply required parameters explicitly. A prompt that is helpful at a console can block or fail a scheduled run. Error messages should let the caller correct the input without reading the function source.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
function Get-ServiceReport {
param(
[Parameter(Mandatory)]
[string] $Name ,
[ValidateSet('Running' , 'Stopped')]
[string] $Status = 'Running' ,
[ValidateRange(1 , 100)]
[int] $First = 5
)
Get-Service -Name $Name |
Where-Object Status -eq $Status |
Select-Object -First $First Name, Status, StartType }
Get-ServiceReport -Name 'W*' -Status Running -First 3- Stage 1function
-Name -Status -First
What happens
Call the function with First set to 0 and then 1 in real PowerShell. The first call should fail binding before the service query. A syntactically valid Name that matches nothing tests a different behavior and should have its own expected outcome.
Worth remembering
Test omitted, invalid, boundary and valid inputs. Validation does not guarantee that the external operation succeeds.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
A function with mandatory, set-restricted and range-checked parameters.
Show reference output
Illustrative output · values vary by environment
Name Status StartType ---- ------ --------- W32Time Running Manual WinDefend Running Automatic WpnService Running Automatic
Keep going
Next: PowerShell SplattingCheck your understanding
A report accepts First between 1 and 100. What should happen when someone supplies 0?
ValidateRange(1,100) rejects the argument during parameter binding, before the function body runs.