Skip to content

Unused variable false positive in ForEach-Object begin block (PSUseDeclaredVarsMoreThanAssignments) #5408

@JohnGurin

Description

@JohnGurin

Prerequisites

  • I have written a descriptive issue title.
  • I have searched all open and closed issues to ensure it has not already been reported.
  • I have read the troubleshooting guide.
  • I am sure this issue is with the extension itself and does not reproduce in a standalone PowerShell instance.
  • I have verified that I am using the latest version of Visual Studio Code and the PowerShell extension.
  • If this is a security issue, I have read the security issue reporting guidance.

Summary

Variables initialized in begin block of ForEach-Object trigger PSUseDeclaredVarsMoreThanAssignments warning.

PowerShell Version

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

Name             : ConsoleHost
Version          : 5.1.26100.7705
InstanceId       : 4ed60023-e437-45ae-b589-226f399acc62
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Visual Studio Code Version

1.109.5
072586267e68ece9a47aa43f8c108e0dcbf44622
x64

Extension Version

ms-vscode.powershell@2025.4.0

Steps to Reproduce

1, 2, 3 | ForEach-Object { $list = @() } { $list += $_ } { $list }
                           ^^^^^
The variable 'list' is assigned but never used.
PSScriptAnalyzer(PSUseDeclaredVarsMoreThanAssignments)

Returning the $list from the begin block offs the warning

1, 2, 3 | ForEach-Object { $list = @(); $list } { $list += $_ } { $list }

Visuals

No response

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugA bug to squash.Needs: TriageMaintainer attention needed!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions