diff --git a/Rules/AvoidAssignmentToAutomaticVariable.cs b/Rules/AvoidAssignmentToAutomaticVariable.cs index 6011300ef..e3b69ff57 100644 --- a/Rules/AvoidAssignmentToAutomaticVariable.cs +++ b/Rules/AvoidAssignmentToAutomaticVariable.cs @@ -44,9 +44,10 @@ public IEnumerable AnalyzeScript(Ast ast, string fileName) if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); IEnumerable assignmentStatementAsts = ast.FindAll(testAst => testAst is AssignmentStatementAst, searchNestedScriptBlocks: true); - foreach (var assignmentStatementAst in assignmentStatementAsts) + foreach (AssignmentStatementAst assignmentStatementAst in assignmentStatementAsts) { - var variableExpressionAst = assignmentStatementAst.Find(testAst => testAst is VariableExpressionAst, searchNestedScriptBlocks: false) as VariableExpressionAst; + var variableExpressionAst = assignmentStatementAst.Left.Find(testAst => testAst is VariableExpressionAst && testAst.Parent == assignmentStatementAst, searchNestedScriptBlocks: false) as VariableExpressionAst; + if (variableExpressionAst == null) { continue; } var variableName = variableExpressionAst.VariablePath.UserPath; if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase)) { diff --git a/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 b/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 index 5709244ab..e2a363da5 100644 --- a/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 +++ b/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 @@ -63,6 +63,20 @@ Describe "AvoidAssignmentToAutomaticVariables" { $warnings.Count | Should -Be 0 } + It "Does not throw a NullReferenceException when using assigning a .Net property to a .Net property (Bug in 1.17.0 - issue 1007)" { + Invoke-ScriptAnalyzer -ScriptDefinition '[foo]::bar = [baz]::qux' -ErrorAction Stop + } + + It "Does not flag properties of a readonly variable (issue 1012)" { + [System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition '$Host.PrivateData["ErrorBackgroundColor"] = "Black"' + $warnings.Count | Should -Be 0 + } + + It "Does not flag RHS of variable assignment (Bug in 1.17.0, issue 1013)" { + [System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition '[foo]::bar = $true' + $warnings.Count | Should -Be 0 + } + It "Setting Variable throws exception in applicable PowerShell version to verify the variables is read-only" -TestCases $testCases_ReadOnlyVariables { param ($VariableName, $ExpectedSeverity, $OnlyPresentInCoreClr)