Skip to content

no-global-vars

PowerShellsuspiciousno fixdefault: offpowershell/psscriptanalyzer

Reports a variable in the global: scope, other than the special variables that PowerShell and its tools use ($global:LASTEXITCODE, $global:ErrorActionPreference, $global:PSDefaultParameterValues and so on).

A global variable is shared by everything in the session, including other modules and the user’s own commands. Two scripts that use the same name change each other’s state, and the value is hard to trace to where it was set.

To fix, pass values as parameters, or use a script: variable.

Reported
...
function Get-Thing { }
function Fetch { }
...
$global:count = 1
$x = $global:count + 1
Set-Item $env:Path -Value $Global:Foo
$script:count = 1
...
powershell:
lint:
rules:
no-global-vars: warn # off (default), warn, error

Enabled by the presets: powershell/psscriptanalyzer.

Suppress one line with sudsy-disable-next-line no-global-vars in a comment of the file’s language.

The same check in other tools. full: Sudsy reports what the upstream rule reports; partial: only part of it, as the last column says.

Tool Rule Match What differs
psscriptanalyzer PSAvoidGlobalVars partial Variables inside strings, and Get-Variable -Scope Global, are not looked at.