Skip to content

Commit 8fdb7ae

Browse files
authored
Merge pull request #836 from bergmeister/FixPSUseDeclaredVarsMoreThanAssignments_MultipleAssignments_Issue833
Fix PSUseDeclaredVarsMoreThanAssignments when variable is assigned more than once to still give a warning
2 parents 49e3fbe + f7e4637 commit 8fdb7ae

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

Rules/UseDeclaredVarsMoreThanAssignments.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,17 @@ private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scrip
166166
// Checks if this variableAst is part of the logged assignment
167167
foreach (VariableExpressionAst varInAssignment in varsInAssignment)
168168
{
169-
inAssignment |= varInAssignment.Equals(varAst);
169+
// Try casting to AssignmentStatementAst to be able to catch case where a variable is assigned more than once (https://github.com/PowerShell/PSScriptAnalyzer/issues/833)
170+
var varInAssignmentAsStatementAst = varInAssignment.Parent as AssignmentStatementAst;
171+
var varAstAsAssignmentStatementAst = varAst.Parent as AssignmentStatementAst;
172+
if (varInAssignmentAsStatementAst != null && varAstAsAssignmentStatementAst != null)
173+
{
174+
inAssignment = varInAssignmentAsStatementAst.Left.Extent.Text.Equals(varAstAsAssignmentStatementAst.Left.Extent.Text, StringComparison.OrdinalIgnoreCase);
175+
}
176+
else
177+
{
178+
inAssignment = varInAssignment.Equals(varAst);
179+
}
170180
}
171181

172182
if (!inAssignment)

Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ function MyFunc2() {
4949
Get-Count | `
5050
Should Be 0
5151
}
52+
53+
It "flags a variable that is defined twice but never used" {
54+
Invoke-ScriptAnalyzer -ScriptDefinition '$myvar=1;$myvar=2' -IncludeRule $violationName | `
55+
Get-Count | `
56+
Should Be 1
57+
}
58+
59+
It "does not flag a variable that is defined twice but gets assigned to another variable and flags the other variable instead" {
60+
$results = Invoke-ScriptAnalyzer -ScriptDefinition '$myvar=1;$myvar=2;$mySecondvar=$myvar' -IncludeRule $violationName
61+
$results | Get-Count | Should Be 1
62+
$results[0].Extent | Should Be '$mySecondvar'
63+
}
5264
}
5365

5466
Context "When there are no violations" {

0 commit comments

Comments
 (0)