PowerShell / PowerShell/PSScriptAnalyzer

PSUseDeclaredVarsMoreThanAssignment not correctly handling global vars assigned to within functions

Open
#698 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Area - Rules Issue - Bug
Dominant language
C#
Stars
2.2k
Forks
414
Avg merge
13h 1m
Merged PRs (30d)
2

Description

This rule does not correctly take into account global variables if they are assigned to within a function.

If I set a global variable and then use it later, I still see a warning that the global variable was assigned to, but never used.

Given the following example:

function InitVars()
{
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We need a global foo")]
    param()

    $global:globalFoo = $false
    $script:scriptFoo = $false
}

function UseVars()
{
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We need a global foo")]
    param()

    if ($global:globalFoo)
    {
        Write-Information "`$global:globalFoo is true"
    }

    if ($scriptFoo)
    {
        Write-Information "`$script:scriptFoo is true"
    }
}

I get the following warning:

  • The variable 'globalFoo' is assigned but never used. (line 6)

There are scenarios where using global variables is still necessary, and so in those few instances I am suppressing PSAvoidGlobalVars. To do that, I have to do the assignment within a method.

As you can see above, it hits with global scoped variables, but not with script scoped variables.

This issue doesn't happen if I leave the global assignment in the root of the file (as opposed to within InitVars, but then I can't use SuppressMessageAttribute.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the supplied InitVars and UseVars example and then trace the PSUseDeclaredVarsMoreThanAssignment rule and its existing tests. Done means the global assignment inside a function is recognized as used when referenced later, while the current script-scoped behavior remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, powershell
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.