PSAvoidDefaultValueForMandatoryParameter: Fix param block and parameter set handling #2121
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Summary
While looking into issue #1623, I noticed that the
PSAvoidDefaultValueForMandatoryParameter
rule has several issues. This PR attempts to resolve them and increase test coverage.Observed issues are:
Rule doesn't flag for parameters which are part of a param block not nested within a function. So the below
.ps1
file contents are not flagged:If a parameter is used in multiple parametersets, only being mandatory in one of them, the rule still flags the parameter if it has a default value. (As raised in issue AvoidDefaultValueForMandatoryParameter mistakenly reported. #1623)
When checking whether a parameter is mandatory, the rule does not validate that mandatory is a named argument of a Parameter Attribute. So the below is flagged:
The below test case is faulty. The tested script definition should cause a violation and isn't due to an issue:
PSScriptAnalyzer/Tests/Rules/AvoidDefaultValueForMandatoryParameter.tests.ps1
Lines 29 to 34 in ea70855
I believe any parameter in the block having
Mandatory=$false
causes the rule to break for subsequent parameters in the block.Fixes #1623
The performance of the old rule and new rule are comparable, whilst flagging more cases. This is running the old test file (correcting for the erroneous test) 1,000 times. Times for each run reported by Pester (
Duration.TotalMilliseconds
field).Note: Caching of the string comparer suggested by copilot as an improvement. Not sure on the effectiveness of this change. Function comment-based help also written mostly by copilot - but reading it, it seems sensible.
PR Checklist
.cs
,.ps1
and.psm1
files have the correct copyright headerWIP:
to the beginning of the title and remove the prefix when the PR is ready.