Skip to content

false variable is assigned but never used recommendation #1354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
seajhawk opened this issue Oct 23, 2019 · 11 comments
Closed

false variable is assigned but never used recommendation #1354

seajhawk opened this issue Oct 23, 2019 · 11 comments

Comments

@seajhawk
Copy link

seajhawk commented Oct 23, 2019

Issue Type: Bug

I'm getting "The variable 'results' is assigned but never used.", but I'm actually using the variable. (recommendation appears on line with "$results = $content ..."

      If ($_ -match "#Fields:\s*(.*)"){
        $fields  = $matches[1].split(",") | ForEach-Object{$_.trim()}
        $results = $content | Where-Object{$_ -notmatch "^#"} | ConvertFrom-Csv -Header $fields
      }
    }
    If (-not $results){
      Write-Verbose "Import-CsvFieldsHeader found no valid content in the file, string or array specified."
    }
    $results

[for my reference - line 304 in autopilot.psm1]

Extension version: 2019.9.0
VS Code version: Code 1.39.2 (6ab598523be7a800d7f3eb4d92d7ab9a66069390, 2019-10-15T15:35:18.241Z)
OS version: Windows_NT x64 10.0.17763

@rjmholt rjmholt transferred this issue from PowerShell/vscode-powershell Oct 23, 2019
@FireInWinter
Copy link

I'm seeing the same thing, but in my case it is in the Begin section of Foreach-Object.
1 | ForEach-Object -Begin { $Test=$true } -Process { $Test }

Shows the message "The variable 'Test' is assigned but never used." on the first part where I assign $Test.

@jasonchester
Copy link

jasonchester commented Mar 19, 2020

Also seeing this issue with variable set in Foreach-Object -Begin scriptblock

file content

0..5 | ForEach-Object -Begin { $n = 100 } -Process { $n++ }

❯ Invoke-ScriptAnalyzer .

RuleName : PSUseDeclaredVarsMoreThanAssignments
Severity : Warning
Line     : 1
Column   : 32
Message  : The variable 'n' is assigned but never used.

❯ $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.0.0
PSEdition                      Core
GitCommitId                    7.0.0
OS                             Darwin 19.3.0 Darwin Kernel Version 19.3.0: Thu Jan  9 20:58:23 PST 2020; root:xnu-6153.81.5~1/RELEASE_X86_64
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

❯ Get-Module PSScriptAnalyzer

Name              : PSScriptAnalyzer
Path              : /Users/jason.chester/.local/share/powershell/Modules/PSScriptAnalyzer/1.18.3/PSScriptAnalyzer.psm1
Description       : PSScriptAnalyzer provides script analysis and checks for potential code defects in the scripts by applying a group of built-in or customized rules on the 
                    scripts being analyzed.
Guid              : d6245802-193d-4068-a631-8863a4342a18
Version           : 1.18.3
ModuleBase        : /Users/jason.chester/.local/share/powershell/Modules/PSScriptAnalyzer/1.18.3
ModuleType        : Script
PrivateData       : {PSData}
AccessMode        : ReadWrite
ExportedAliases   : {}
ExportedCmdlets   : {[Get-ScriptAnalyzerRule, Get-ScriptAnalyzerRule], [Invoke-Formatter, Invoke-Formatter], [Invoke-ScriptAnalyzer, Invoke-ScriptAnalyzer]}
ExportedFunctions : {}
ExportedVariables : {}
NestedModules     : {Microsoft.Windows.PowerShell.ScriptAnalyzer}

@bergmeister
Copy link
Collaborator

@FireInWinter @jasonchester Your use cases is already reported in issues #1031
The rule is unfortunately limited to the scope of one script block, therefore this might stay an issue for a while

@FireInWinter
Copy link

@bergmeister If it is limited to one script block, I would say the rule is fairly useless and should be removed until a solution is found. I see so many false positives on this rule, that it makes using PSScriptAnalyzer annoying to use. Is there at least an easy way to disable the rule without editing files in the mod? If I could set something up in my profile to ignore the rule that would at least make PSScriptAnalyzer useful until this is solved.

@bergmeister
Copy link
Collaborator

bergmeister commented Mar 19, 2020

@FireInWinter We've had this discussion over and over again. Yes, there are some false positives but the rule is still very useful in flagging unused variables. It's just up to you to suppress when you know it is a false positive. If you do not want to keep up with that, use the -ExcludeRule switch on Invoke-ScriptAnalyzer or the equivalent of it in a PSSA settings file, to which you can point the vs-code extension.
Here is an example repo where I show this for a git repo: https://github.com/bergmeister/PSScriptAnalyzer-VSCodeIntegration
For global suppression, set the VS-Code user setting "powershell.scriptAnalysis.settingsPath" to where your PSSA settings file is. The settings file (file extension is .psd1) would have the following content:

@{
    ExcludeRules = @(
        'PSAvoidUsingCmdletAliases'
    )
}

@sba923
Copy link

sba923 commented May 12, 2020

How would I disable the rule for some specific variables / code sections in a PS script that I know trigger a false positive, rather than disabling the rule globally?

@bergmeister
Copy link
Collaborator

@sba923 The Readme has a section describing how to suppress them for individual functions or scripts: https://github.com/powershell/psscriptanalyzer#suppressing-rules
For a function, this is how you can suppress for a specific variable (for a script you just put a param() block at the top in order to place the suppression attribute)

function foo {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'unused',
        Justification = 'Reason why it is a false positive')]
    param()

    $unused = $null
}

@sba923
Copy link

sba923 commented May 15, 2020

Thanks a bunch for sharing this!

@joeskeen
Copy link

@sba923 The Readme has a section describing how to suppress them for individual functions or scripts: https://github.com/powershell/psscriptanalyzer#suppressing-rules
For a function, this is how you can suppress for a specific variable (for a script you just put a param() block at the top in order to place the suppression attribute)

function foo {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'unused',
        Justification = 'Reason why it is a false positive')]
    param()

    $unused = $null
}

How do you suppress it in a [ScriptBlock]? I'm seeing it a lot in my Pester unit tests, which are made of lots of script blocks but no functions.

@bergmeister
Copy link
Collaborator

@joeskeen You could put a Param() at the top of the Pester file and put the suppression attributes on top of that. I know, not great terms of scoping, but it works at least

@rjmholt
Copy link
Contributor

rjmholt commented Feb 9, 2021

Duplicate of #1163

@rjmholt rjmholt marked this as a duplicate of #1163 Feb 9, 2021
@rjmholt rjmholt closed this as completed Feb 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

8 participants