Skip to content

Analyzer for Type Reassignment in foreach Loop #1710

Open
@aolszowka

Description

@aolszowka

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…

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