Skip to content

PSUseDeclaredVarsMoreThanAssignment not correctly handling global vars assigned to within functions #698

@HowardWolosky

Description

@HowardWolosky

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions