Mandatory and default parameters of a function Mandatory and default parameters of a function powershell powershell

Mandatory and default parameters of a function


The Mandatory parameter attribute flag:

[Parameter(Mandatory=$true)]

really means "It is mandatory for the caller to supply an argument to this parameter".

If you want a parameter to fall back to a default value that you provide in the param block, set the Mandatory flag to $false:

[Parameter(Mandatory=$false)][string]$EmailTo = "to@company.domain",

This may seem a little counter-intuitive, but it allows you to detect when a user didn't supply a parameter that is needed:

if(-not($PSBoundParameters.ContainsKey('EmailTo')) -and $EmailTo){    # User relied on default value}