PowerShell / PowerShell/PSScriptAnalyzer

Analyzer for Type Reassignment in `foreach` Loop

Open
#1,710 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Summary of the new feature
Consider the following script:

if ($true) {
    [String]$MyVar = "Blah"
}

[int[]]$MyInts = @(1,2,3)
foreach ($MyVar in $MyInts) {
    Write-Host "This is my type [$($MyVar.GetType())]"
}

A naïve C# reading of the above PowerShell would assume that the above would print out:

This is my type [int]
This is my type [int]
This is my type [int]

However this is PowerShell and due to Scoping Rules this actually returns:

This is my type [string]
This is my type [string]
This is my type [string]

Proposed technical implementation details (optional)

This has already burned me once in production.

As far as I can tell there is not an existing analyzer to determine this.

It is unclear if it is even feasible to do this reliably.

What is the latest version of PSScriptAnalyzer at the point of writing

PS > Get-Module | Where-Object {$_.Name -eq 'PSScriptAnalyzer' }

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     1.19.1                PSScriptAnalyzer                    {Get-ScriptAnalyzerRule, Invoke-Formatter, Invoke…

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

No source file, test, or entry point is named. Start by reviewing the existing analyzer rules and the linked PowerShell scoping rules, then determine whether type reassignment in foreach loops can be detected reliably. Done means a documented analyzer diagnostic with tests covering the example behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, powershell
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.