Home > OS >  powershell lint says variable assigned but never used. no i am using
powershell lint says variable assigned but never used. no i am using

Time:11-05

Goal

I want to know, why am I getting this message?

The variable 'existModuleName' is assigned but never used.PSScriptAnalyzer(PSUseDeclaredVarsMoreThanAssignments)

enter image description here

If possible, I want to rewrite the code so that the message is not displayed.

And I want to know, Is this bug or syntax error?

Code

function Get-SayHeyYou {
    param(
    )
    [bool]$existModuleName = $false
    (1..3) | ForEach-Object {
        if ($_ -eq 2) {
            $existModuleName = $true
        }
    }
    if ($existModuleName) {
        Write-Host "hey you!"
    }
}

Get-SayHeyYou

My thinking

After first assigning $false. When $_ is 2, $true is assigned by if, And used in the last if.

What's more, when I run this code, it says "hey you!" As expected. I don't think there is any problem with the scope of variables.

Tried

I tried to add Write-Host $existModuleName.

function Get-SayHeyYou {
    param(
    )
    [bool]$existModuleName = $false
    (1..3) | ForEach-Object {
        if ($_ -eq 2) {
            $existModuleName = $true
        }
    }
    if ($existModuleName) {
        Write-Host "hey you!"
        Write-Host $existModuleName
    }
}

Get-SayHeyYou

I added Write-Host $ existModuleName. There seems to be no particular change.

The output of this code is below.

hey you!
True

Environment

  • Powershell 7.1.5

  • Windows 10 Pro 21H1

  • VSCode

    • Version: 1.61.2 (system setup)
    • Commit: 6cba118ac49a1b88332f312a8f67186f7f3c1643
    • Date: 2021-10-19T14:57:20.575Z
    • Electron: 13.5.1
    • Chrome: 91.0.4472.164
    • Node.js: 14.16.0
    • V8: 9.1.269.39-electron.0
    • OS: Windows_NT x64 10.0.19043

CodePudding user response:

This is a well-known false positive in PSScriptAnalyzer. You are not doing anything wrong.

You may disable it inline with a special attribute, like so:

function Get-SayHeyYou {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'existModuleName',
        Justification = 'variable is used in another scope')]
    param()
    [bool]$existModuleName = $false
    (1..3) | ForEach-Object {
        if ($_ -eq 2) {
            $existModuleName = $true
        }
    }
    if ($existModuleName) {
        Write-Host "hey you!"
    }
}

Get-SayHeyYou

If you prefer not to modify the code, you could also completely disable the rule by having a file containing your PSScriptAnalyzer settings, and then you can point vscode to look at it. See also this comment and some of the others.

Also here is a sample repository showing use with vscode and custom rule settings.

The disadvantage of disabling the rule completely is that you will miss legitimate times when you assigned a variable without using it.

But this is currently the tradeoff we must contend with.

頑張ってね!

  • Related