Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PSProvideDefaultParameterValue should automatically ignore mandatory parameters #360

Closed
mikefrobbins opened this issue Nov 13, 2015 · 4 comments

Comments

@mikefrobbins
Copy link

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.

@raghushantha
Copy link
Member

Mike. Thank you for the issue.

Will fix the Mandatory parameter issue and create a new warning rule regarding using default values for Mandatory parameters.

@Jaykul
Copy link

Jaykul commented Nov 17, 2015

#362

@mikefrobbins
Copy link
Author

I hadn't thought of the larger problem that Joel mentions in issue #362, only the warning I was receiving where it wasn't possible to set a default value. I do agree with Joel as I honestly don't see the value of the PSProvideDefaultParameterValue rule. How does setting a default value have anything to do with best practices?

I do think a rule should exist to warn a user if they're trying to use a default value with a mandatory parameter as previously referenced.

@raghushantha
Copy link
Member

Reworked the Mandatory parameter rule as per this thread

#382

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants