Skip to content

Commit 98e8d3a

Browse files
committed
Merge pull request #191 from PowerShell/FixGlobalVars
Add check for builtin variables for GlobalVar rule
2 parents f6ba095 + 7a1215a commit 98e8d3a

File tree

4 files changed

+28
-11
lines changed

4 files changed

+28
-11
lines changed

Engine/Helper.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,24 @@ public bool IsVariableGlobalOrEnvironment(VariableExpressionAst varAst, Ast ast)
494494
return VariableAnalysisDictionary[ast].IsGlobalOrEnvironment(varAst);
495495
}
496496

497+
498+
/// <summary>
499+
/// Checks whether a variable is a global variable.
500+
/// </summary>
501+
/// <param name="ast"></param>
502+
/// <returns></returns>
503+
public bool IsVariableGlobal(VariableExpressionAst varAst)
504+
{
505+
//We ignore the use of built-in variable as global variable
506+
if (varAst.VariablePath.IsGlobal)
507+
{
508+
string varName = varAst.VariablePath.UserPath.Remove(varAst.VariablePath.UserPath.IndexOf("global:", StringComparison.OrdinalIgnoreCase), "global:".Length);
509+
return !SpecialVars.InitializedVariables.Contains(varName, StringComparer.OrdinalIgnoreCase);
510+
}
511+
return false;
512+
}
513+
514+
497515
/// <summary>
498516
/// Checks whether all the code path of ast returns.
499517
/// Runs InitializeVariableAnalysis before calling this method

Rules/AvoidGlobalVars.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
4141
{
4242
foreach (VariableExpressionAst varAst in varAsts)
4343
{
44-
if (varAst.VariablePath.IsGlobal)
44+
if (Helper.Instance.IsVariableGlobal(varAst))
4545
{
4646
yield return
4747
new DiagnosticRecord(

Tests/Rules/AvoidGlobalOrUnitializedVars.ps1

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
$Global:1 = "Globalization?"
1+
$Global:1 = "globalVar
2+
$Global:DebugPreference
3+
4+
25

36
function NotGlobal {
47
$localVars = "Localization?"

Tests/Rules/AvoidGlobalOrUnitializedVarsNoViolations.ps1

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
function Test {
1+
$Global:DebugPreference
2+
3+
4+
function Test {
25
$initialized = "Initialized"
36
$noglobal = "local"
47
$env:ShouldNotRaiseError
@@ -31,18 +34,11 @@ $proc[0]
3134

3235
function Test-PreferenceVariable
3336
{
34-
Param(
35-
[switch]
36-
$a,
37-
38-
[System.Management.Automation.SwitchParameter]
39-
$b
40-
)
4137

4238
if (-not $PSBoundParameters.ContainsKey('Verbose')) {
4339
$VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') -as
4440
[System.Management.Automation.ActionPreference]
4541
}
4642

4743
$VerbosePreference
48-
}
44+
}

0 commit comments

Comments
 (0)