From df0630c4640578bc6c17094ee54d1992b5e183ac Mon Sep 17 00:00:00 2001 From: Liam Peters Date: Wed, 27 Mar 2024 15:28:48 +0000 Subject: [PATCH] AvoidAssignmentToAutomaticVariable: Ignore when a Parameter has an Attribute that contains a Variable expression, such as '[ValidateSet($True,$False)]'. --- Rules/AvoidAssignmentToAutomaticVariable.cs | 7 ++++++- Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Rules/AvoidAssignmentToAutomaticVariable.cs b/Rules/AvoidAssignmentToAutomaticVariable.cs index c188da341..8188ccb70 100644 --- a/Rules/AvoidAssignmentToAutomaticVariable.cs +++ b/Rules/AvoidAssignmentToAutomaticVariable.cs @@ -89,7 +89,12 @@ public IEnumerable AnalyzeScript(Ast ast, string fileName) { continue; } - + // also check the parent to exclude variableExpressions that appear within attributes, + // such as '[ValidateSet($True,$False)]' where the read-only variables $true,$false appear. + if (variableExpressionAst.Parent is AttributeAst) + { + continue; + } if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase)) { yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableError, variableName), diff --git a/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 b/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 index 8130990c2..e9cc5331f 100644 --- a/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 +++ b/Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1 @@ -94,6 +94,13 @@ Describe "AvoidAssignmentToAutomaticVariables" { $warnings.Count | Should -Be 0 } + It "Does not flag true or false being used in ValidateSet" { + # All other read-only automatic variables cannot be used in ValidateSet + # they result in a ParseError. $true and $false are permitted however. + [System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'param([ValidateSet($true,$false)]$MyVar)$MyVar' -ExcludeRule PSReviewUnusedParameter + $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 }