Search notes:

Powershell: Param(Parameter(Mandatory=$true|$false))

By default, in PowerShell, assigning a value to a parameter is optional when a function is called.
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 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:

Check if parameter was passed

The following script uses the automatic variable $psBoundParameters to check if an optional parameter was specfied when script was invoked.
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"
}
Github repository about-PowerShell, path: /language/statement/function/parameters/attributes/parameter/mandatory/psBoundParameters.ps1

See also

Function and script parameter attributes

Index