PowerShell / PSScriptAnalyzer

Download ScriptAnalyzer from PowerShellGallery
https://www.powershellgallery.com/packages/PSScriptAnalyzer/
MIT License
1.85k stars 373 forks source link

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

Closed rmguilbault closed 1 year ago

rmguilbault commented 1 year ago

Prerequisites

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

ms-vscode.powershell@2023.6.0

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

bergmeister commented 1 year ago

This is a known issue (see e.g. #1163) as this rule is limited to per scriptblock analysis, which is a hard problem to solve and I don't expect that effort to be made.

ghost commented 1 year ago

This issue has been marked as duplicate and has not had any activity for 1 day. It will be closed for housekeeping purposes.