Skip to content
AgileLogics
5 min read

Script Parameters

Prerequisites: Your first script

A param() block at the top of a script defines parameters — named inputs, just like a cmdlet's.

Set-Content greet.ps1 @'
param(
  [Parameter(Mandatory)]
  [string]$Name,

  [int]$Times = 1,

  [switch]$Shout
)

foreach ($i in 1..$Times) {
  $message = "Hello, $Name!"
  if ($Shout) { $message = $message.ToUpper() }
  $message
}
'@

./greet.ps1 -Name Ada
./greet.ps1 -Name Linus -Times 2 -Shout
./greet.ps1 Grace
Hello, Ada!
HELLO, LINUS!
HELLO, LINUS!
Hello, Grace!
  • Each parameter can have a type ([string], [int]) — PowerShell converts and checks the values for you.
  • A default value ($Times = 1) is used when the parameter isn't given.
  • [switch] parameters are on/off flags: present means $true.
  • [Parameter(Mandatory)] makes a parameter required. If it's missing in an interactive session, PowerShell prompts for it; in automation, it's an error.
  • Parameters can be passed by name in any order, or by position.

Tab completion works for your script's parameters too — type ./greet.ps1 - and press Tab.

Validating input

Set-Content deploy.ps1 @'
param(
  [ValidateSet('dev', 'test', 'prod')]
  [string]$Environment = 'dev',

  [ValidateRange(1, 10)]
  [int]$Instances = 1
)
"Deploying $Instances instance(s) to $Environment"
'@

./deploy.ps1 -Environment prod -Instances 3
try { ./deploy.ps1 -Environment staging } catch { $_.Exception.Message }
Deploying 3 instance(s) to prod
Cannot validate argument on parameter 'Environment'. The argument "staging" does not belong to the set "dev,test,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.

Validation attributes reject bad input before the script runs, with a clear message — and ValidateSet also gives tab completion of the allowed values.

Common mistakes

  • Putting code before the param() block — it must be the first statement in the script (after comments).
  • Using $args instead of a param() block. $args holds unnamed arguments, but named, typed parameters are far clearer and safer.