Parameter attributes help control how users give input to your script. Mandatory makes sure a value is given. ValidateSet limits input to specific choices.
0
0
Parameter attributes (Mandatory, ValidateSet) in PowerShell
Introduction
You want to make sure a user always provides a value for a script parameter.
You want to restrict input to a few allowed options to avoid mistakes.
You are writing a script that needs specific settings chosen from a list.
You want to guide users to enter only valid values without extra checks.
Syntax
PowerShell
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Option1', 'Option2', 'Option3')]
[string]$ParameterName
)Mandatory=$true means the user must provide this parameter.
ValidateSet lists allowed values; PowerShell will error if input is outside this set.
Examples
This parameter
$Name must be provided by the user.PowerShell
param(
[Parameter(Mandatory=$true)]
[string]$Name
)This parameter
$Color only accepts 'Red', 'Green', or 'Blue'.PowerShell
param(
[ValidateSet('Red', 'Green', 'Blue')]
[string]$Color
)This parameter
$Action is required and must be one of the three options.PowerShell
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Start', 'Stop', 'Restart')]
[string]$Action
)Sample Program
This script requires the user to provide an $Operation parameter. It must be 'Add', 'Remove', or 'Update'. The script then prints the chosen operation.
PowerShell
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Add', 'Remove', 'Update')]
[string]$Operation
)
Write-Output "You chose the operation: $Operation"OutputSuccess
Important Notes
If a mandatory parameter is missing, PowerShell will prompt the user to enter it.
Using ValidateSet helps prevent typos and invalid inputs.
You can combine Mandatory and ValidateSet to make sure input is both required and valid.
Summary
Mandatory makes a parameter required.
ValidateSet limits input to specific allowed values.
Together, they help make scripts safer and easier to use.