It is possible to mark a parameter as mandatory with Param([Parameter(Mandatory=$true)…]) and to explicitly mark the parameter as optional with Param([Parameter(Mandatory=$false)…]).
A parameter's data type can optionally be specified after the [parameter(…)] declaration:
function FUNC {
param (
[parameter(mandatory=$true)][int] $val
)
…
}
Powershell will ask to provide a value for required parameters if they're not specified when the function is invoked:
PS C:\> FUNC
cmdlet FUNC at command pipeline position 1
Supply values for the following parameters:
val:
param (
[parameter(mandatory=$true )] $req,
[parameter(mandatory=$false)] $opt
)
set-strictMode -version latest
write-host "req = $req"
if ($opt -eq $null) {
#
# The value of the parameter 'opt' is null
# This is either …
#
if ($psBoundParameters.containsKey('opt')) {
#
# … because the invoker has explicitely
# passed $null as value for the paramter …
#
write-host "opt was passed as null"
}
else {
#
# … or because
# the paramter was not set (in which
# case it defaults to $null).
#
write-host "opt was not passed (and is therefore null)"
}
}
else {
write-host "opt = $opt"
}