Skip to content

PSUseDeclaredVarsMoreThanAssignments: False positive when using ForEach-Object in special cases #934

Closed
@bergmeister

Description

@bergmeister

Extracted from this comment here:

Steps to reproduce

$Doubles = 1..100 | ForEach { $collect = @() } { $Collect += $_ * 2 } { $Collect }
$Requirement = Get-Item .
[hashtable]$hash = $Requirement.PSObject.Properties.Where{$_.Value} | ForEach-Object { $ht = @{} } { $ht.Add($_.Name, $_.value) } { $ht }
$hash

Expected behavior

No PSUseDeclaredVarsMoreThanAssignments warnings

Actual behavior

1 or more PSUseDeclaredVarsMoreThanAssignments warnings in both cases

RuleName                            Severity     ScriptName Line  Message
--------                            --------     ---------- ----  -------
PSUseDeclaredVarsMoreThanAssignment Warning      a.ps1      2     The variable 'ht' is assigned but never used.
s
RuleName                            Severity     ScriptName Line  Message
--------                            --------     ---------- ----  -------
PSUseDeclaredVarsMoreThanAssignment Warning      a.ps1      1     The variable 'Doubles' is assigned but never used.
s
PSUseDeclaredVarsMoreThanAssignment Warning      a.ps1      1     The variable 'collect' is assigned but never used.
s
PSAvoidUsingCmdletAliases           Warning      a.ps1      1     'ForEach' is an alias of 'ForEach-Object'. Alias can
                                                                  introduce possible problems and make scripts hard to
                                                                  maintain. Please consider changing alias to its full
                                                                  content.

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 # or the latest development branch

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