PowerShell / PowerShell/PSScriptAnalyzer

PSUseDeclaredVarsMoreThanAssignments is not aware of Pester's scoping

Open
#946 9 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Steps to reproduce

Supposing a Pester Test file like below:

$here = $PsScriptRoot

Describe 'My Module' {

    BeforeAll { $module = Import-Module "$here\MyModule.psd1" }
    AfterAll  { $module | Remove-Module -Force }

    It 'can be loaded' {
        $module | Should Not Be $null
     }
}

Expected behavior

No warning on the $module variable, as it is used in the code below.

Actual behavior

Invoke-ScriptAnalyzer reports the following:

PSUseDeclaredVarsMoreThanAssignments  Warning  My.Tests.ps1 5  The variable 'module' is assigned but never used.

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.16299.251
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.16299.251
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

> (Get-Module -ListAvailable PSScriptAnalyzer).Version | ForEach-Object { $_.ToString() }

1.16.1
1.16.0
1.15.0
1.14.1
1.14.0
1.13.0
1.12.0
1.11.1
1.11.0
1.10.0
1.9.0
1.8.1
1.8.0
1.7.0
1.6.0
1.5.0
1.4.0
1.3.0
1.2.0
1.1.1
1.1.0
1.0.2
1.0.1
1.0

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 Pester example and inspect the PSUseDeclaredVarsMoreThanAssignments rule, focusing on how it tracks variables across BeforeAll, AfterAll, and It blocks. Done means the sample no longer reports $module as assigned but unused, while the rule continues to identify genuinely unused assignments.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.