Skip to content

"Variable assigned but never used" false positive in a script block passed to ForEach-Object #1942

Closed as not planned
@ForNeVeR

Description

@ForNeVeR

Steps to reproduce

(Initially reported in downstream repo, see ant-druha/intellij-powershell#96, but with my adjustments to better demonstrate the behavior.)

(1..3) | ForEach-Object {
    $Hashes = "test"
} {
    $Hashes += "Some-String "
} {
    $Hashes
}

Expected behavior

There should be no warnings about the initial value of the $Hashes variable not being used in this code.

To demonstrate that it is in fact used, run the code, and you'll see output testSome-String Some-String Some-String: test value was used.

Actual behavior

The variable 'Hashes' is assigned but never used.PSScriptAnalyzer(PSUseDeclaredVarsMoreThanAssignments)

Environment data

While it was reported in intellij-powershell where we bundle v1.21.0, I was also able to reproduce the same in VSCode.

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      7.3.7
PSEdition                      Core
GitCommitId                    7.3.7
OS                             Microsoft Windows 10.0.22621
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

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

Additional Information

From a quick look, it may be related to #1472.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions