FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

PSAvoidDefaultValueForMandatoryParameter: Fix param block and parameter set handling by liamjpeters · Pull Request #2121 · PowerShell/PSScriptAnalyzer · GitHub

PSAvoidDefaultValueForMandatoryParameter: Fix param block and parameter set handling - #2121

Merged
Andy Jordan (andyleejordan) merged 4 commits into
PowerShell:mainfrom
liamjpeters:#1623AvoidDefaultValueForMandatoryParameter
Oct 15, 2025
Merged

PSAvoidDefaultValueForMandatoryParameter: Fix param block and parameter set handling#2121
Andy Jordan (andyleejordan) merged 4 commits into
PowerShell:mainfrom
liamjpeters:#1623AvoidDefaultValueForMandatoryParameter

Conversation

Liam Peters (liamjpeters) commented Aug 18, 2025
edited
Loading

Copy link
Copy Markdown
Contributor

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:

  1. 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:

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        $Parameter1 = 'default Value'
    )
  2. 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)

    function Test
    {
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory, ParameterSetName = "Mandatory")]
            [Parameter(ParameterSetName = "Optional")]
            $Parameter1 = 'default Value'
        )
    }
  3. 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:

    function Test {
        [CmdletBinding()]
        Param
        (
            [MyAttribute(Mandatory)]
            $Parameter1 = 'default Value'
        )
    }
  4. The below test case is faulty. The tested script definition should cause a violation and isn't due to an issue:

    Context "When there are no violations" {
    It "has 1 provide default value for mandatory parameter violation" {
    $violations = Invoke-ScriptAnalyzer -ScriptDefinition 'Function foo{ Param([Parameter(Mandatory=$false)]$Param1=''val1'', [Parameter(Mandatory)]$Param2=''val2'', $Param3=''val3'') }' |
    Where-Object { $_.RuleName -eq $ruleName }
    $violations.Count | Should -Be 0
    }

    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).

Average (ms) Min (ms) Max (ms)
Old Rule 108.68 92.74 174.55
New Rule 105.28 85.46 195.63

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

Comment on lines +90 to +92
.ToList();

return parameterAttributes.Count > 0 &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

I believe the ToList and Count > 0 checks are unnecessary and that you can simple return .Where(...).All(...) directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

All(...) on an empty sequence returns true - which changes things.

The function returns true if the parameter has [Parameter()] attributes AND all of them were mandatory. Perhaps the name could be clearer.

I need an AllButDefinitelyAtLeastOnePlease(...) 🤔. Does that exist? 😅

Andy Jordan (andyleejordan) Oct 14, 2025
edited
Loading

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

You are quite right about that because of the nuance with And(...) but we can still get rid of the ToList() (and a stray boolean comparison):

    var parameterAttributes = paramAst.Attributes.OfType<AttributeAst>()
        .Where(attr => string.Equals(attr.TypeName?.Name, "parameter", StringComparison.OrdinalIgnoreCase));

    return parameterAttributes.Any() &&
        parameterAttributes.All(attr =>
            attr.NamedArguments?.OfType<NamedAttributeArgumentAst>()
                .Any(namedArg => string.Equals(namedArg?.ArgumentName, "mandatory", StringComparison.OrdinalIgnoreCase)
                    && Helper.Instance.GetNamedArgumentAttributeValue(namedArg)));

And I like how that reads: where, any and all which matches the description of the function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

The stray boolean comparison looks funky, I agree. Without it I got a bool? to bool implicit cast issue.

That nullable bool is coming from the null-conditional in attr.NamedArguments?..

Checking it shows it's not actually required, NamedArguments is always at least an empty ReadOnlyCollection.

https://github.com/PowerShell/PowerShell/blob/26bb188c8be0cda6cb548ce1a12840ebf67e1331/src/System.Management.Automation/engine/parser/ast.cs#L2185-L2193

I'll make those changes

Liam Peters (liamjpeters) force-pushed the #1623AvoidDefaultValueForMandatoryParameter branch from 715b2a7 to 35d42c1 Compare October 15, 2025 08:28

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Thanks!

Andy Jordan (andyleejordan) merged commit dc55078 into PowerShell:main Oct 15, 2025
4 checks passed
Liam Peters (liamjpeters) deleted the #1623AvoidDefaultValueForMandatoryParameter branch October 15, 2025 19:13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AvoidDefaultValueForMandatoryParameter mistakenly reported.

2 participants


Back | FazBrowse Home | New Git URL