Description
When a parameter is set as mandatory, it is not possible to set a default value. If a default value is set for a mandatory parameter, the default value will never be used.
To reproduce the problem, create a function with a mandatory parameter:
function Test-MandatoryParam {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[String]$Name
)
Write-Output $Name
}
Running Script Analyzer against that function:
Invoke-ScriptAnalyzer -Path C:\tmp\Test-MandatoryParam.ps1
That will give the following warning:
Parameter 'Name' is not initialized. Parameters must have a default value. To fix a violation of this rule, please specify a default value for all parameters.
To show that default values can NOT be used with mandatory parameters, add a default value to the name parameter:
function Test-MandatoryParam {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[String]$Name = 'Mike'
)
Write-Output $Name
}
Run the function. The default value will not be used and you will be prompted for a value:
PS C:> Test-MandatoryParam
cmdlet Test-MandatoryParam at command pipeline position 1
Supply values for the following parameters:
Name:
Expected behavior is to automatically ignore this rule when a parameter has been defined as mandatory. To be thorough, a rule should exist to give a warning or error when a default value is specified with a mandatory parameter since that value will never be used.