PowerShell / PSScriptAnalyzer

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

Global variables are erroneously reported as "never used" #1300

Open SetTrend opened 5 years ago

SetTrend commented 5 years ago

System Details Output

### VSCode version: 1.36.1 2213894ea0415ee8c85c5eea0d0ff81ecc191529 x64

### VSCode extensions:
bierner.lit-html@1.11.0
mikeburgh.xml-format@1.0.2
MS-CEINTL.vscode-language-pack-de@1.36.2
ms-vscode.powershell@2019.5.0
msjsdiag.debugger-for-chrome@4.11.6
slevesque.vscode-hexdump@1.7.2

### PSES version:

### PowerShell version:

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

Issue Description

PowerShell extension reports global variables as assigned but not used when they are not used from within a .psm1 module file. However, global variables may be used by scripts outside that module importing it.

Expected Behaviour

Global variables should never be reported as being unused.

Actual Behaviour

PowerShell extension reports global variables as assigned but not used when they are not used from within a .psm1 module file.

global variables error

bergmeister commented 5 years ago

I agree with you that global variables should be included from the analysis as that's their nature and there is a separate rule that discourages them anyway, so I'd be happy to accept a PR with such a change

NapAlot commented 3 years ago

I have this issue as well. it seems that The analyzer should be aware of $Global:var as being in the host script outside the function as $var.

image

NapAlot commented 3 years ago

I agree with you that global variables should be included from the analysis as that's their nature and there is a separate rule that discourages them anyway, so I'd be happy to accept a PR with such a change

Global variables are discouraged? What should be used in place of them?

NapAlot commented 3 years ago

I was able to resolve my issues by setting my $global: to $script: