Skip to content

PSScriptAnalyzer: "The variable <variable> is assigned but never used" false error within ForEach-Object scope #1927

@ghost

Description

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

When I declare a local variable and try to set it within the ForEach-Object scope.

image

PowerShell Version

PS C:\Users\rguilbault\Documents\Projects\MTDSCLib> $PSVersionTable

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

Visual Studio Code Version

code --version
1.79.2
695af097c7bd098fbf017ce3ac85e09bbc5dda06
x64

Extension Version

code --list-extensions --show-versions | Select-String powershell

[email protected]

Steps to Reproduce

I get an error on the $success = $true line here:

function Test-LinterError {
$success = $false
@(1) | ForEach-Object {
$success = $true
}
return $success
}

and here:

function Test-LinterError {
$success = $false
{
$success = $true
}
return $success
}

I do not get such lint errors for any of these blocks:

function Test-LinterError {
$success = $false
if(1) {
$success = $true
}
return $success
}

function Test-LinterError {
$success = $false
foreach($item in @(1)) {
$success = $true
}
return $success
}

in the first situation (the one of interest), $success is properly side effected from within the ForEach-Object block such that returning it is meaningful use, i.e. the function returns $true.

contrarily, the second situation (the raw block/scope), I get that $success there is local to that scope and it test out as expected (e.g. the function returns $false).

I have scoured documentation looking for any explanation to justify the linter error, but I think it is simply a bug and perhaps not a commonly enough used coding pattern for anybody to have noticed/cared about it. I am willing to concede the point if someone can show me the documentation that explains why my expectation is flawed, though.

Visuals

No response

Logs

No response

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