GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — PSAvoidDefaultValueForMandatoryParameter: Fix param block and parameter set handling by liamjpeters · Pull Request #2121 · PowerShell/PSScriptAnalyzer

Conversation

@liamjpeters

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

Uh oh!

There was an error while loading. Please reload this page.

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:

    PSScriptAnalyzer/Tests/Rules/AvoidDefaultValueForMandatoryParameter.tests.ps1

    Lines 29 to 34 in ea70855

    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

  • PR has a meaningful title
    • Use the present tense and imperative mood when describing your changes
  • Summarized changes
  • Change is not breaking
  • Make sure all .cs, .ps1 and .psm1 files have the correct copyright header
  • Make sure you've added a new test if existing tests do not effectively test the code changed and/or updated documentation
  • This PR is ready to merge and is not Work in Progress.
    • If the PR is work in progress, please add the prefix WIP: to the beginning of the title and remove the prefix when the PR is ready.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@liamjpeters
Liam Peters (liamjpeters) requested review from Andy Jordan (andyleejordan) and Christoph Bergmeister (bergmeister) as code owners August 18, 2025 15:22
andyleejordan
Andy Jordan (andyleejordan) suggested changes Oct 13, 2025
View reviewed changes
Comment thread Rules/AvoidDefaultValueForMandatoryParameter.cs Outdated
Comment on lines +90 to +92
.ToList();

return parameterAttributes.Count > 0 &&

@andyleejordan Andy Jordan (andyleejordan) Oct 13, 2025

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

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

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@liamjpeters Liam Peters (liamjpeters) Oct 14, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

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? 😅

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@andyleejordan Andy Jordan (andyleejordan) Oct 14, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

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.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

liamjpeters reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

@liamjpeters Liam Peters (liamjpeters) Oct 15, 2025

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

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

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

andyleejordan reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
Comment thread Rules/AvoidDefaultValueForMandatoryParameter.cs Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Rules/AvoidDefaultValueForMandatoryParameter.cs Resolved

Uh oh!

There was an error while loading. Please reload this page.

Liam Peters (liamjpeters) added 3 commits October 15, 2025 09:28
@liamjpeters
Updated rule
1c5e9ff
@liamjpeters
Remove no-longer relevant comment
4819de4
@liamjpeters
Inline unnecessary function calls
35d42c1
@liamjpeters
Liam Peters (liamjpeters) force-pushed the #1623AvoidDefaultValueForMandatoryParameter branch from 715b2a7 to 35d42c1 Compare October 15, 2025 08:28
@liamjpeters
Tidy up HasMandatoryInAllParameterAttributes
06ee71d
andyleejordan
Andy Jordan (andyleejordan) approved these changes Oct 15, 2025
View reviewed changes

@andyleejordan Andy Jordan (andyleejordan) left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Thanks!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@andyleejordan
Andy Jordan (andyleejordan) enabled auto-merge (squash) October 15, 2025 18:29
@andyleejordan
Andy Jordan (andyleejordan) merged commit dc55078 into PowerShell:main Oct 15, 2025
@liamjpeters
Liam Peters (liamjpeters) deleted the #1623AvoidDefaultValueForMandatoryParameter branch October 15, 2025 19:13
@FH-Inway Florian Hopfner (FH-Inway) mentioned this pull request Jun 16, 2026
Get-D365Database - Fix DatabaseName parameter not used for SQL connection d365collaborative/d365fo.tools#905
Merged
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@bergmeister Christoph Bergmeister (bergmeister) Awaiting requested review from bergmeister bergmeister is a code owner
1 more reviewer
@andyleejordan Andy Jordan (andyleejordan) andyleejordan approved these changes
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

AvoidDefaultValueForMandatoryParameter mistakenly reported.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@liamjpeters @andyleejordan
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.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.