Skip to content

Commit aa7a582

Browse files
AvoidAssignmentToAutomaticVariable: Ignore when a Parameter has an Attribute that contains a Variable expression, such as '[ValidateSet($True,$False)]'. (#1988)
Co-authored-by: Christoph Bergmeister <[email protected]>
1 parent 03beb17 commit aa7a582

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

Diff for: Rules/AvoidAssignmentToAutomaticVariable.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,12 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
8989
{
9090
continue;
9191
}
92-
92+
// also check the parent to exclude variableExpressions that appear within attributes,
93+
// such as '[ValidateSet($True,$False)]' where the read-only variables $true,$false appear.
94+
if (variableExpressionAst.Parent is AttributeAst)
95+
{
96+
continue;
97+
}
9398
if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase))
9499
{
95100
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableError, variableName),

Diff for: Tests/Rules/AvoidAssignmentToAutomaticVariable.tests.ps1

+7
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,13 @@ Describe "AvoidAssignmentToAutomaticVariables" {
9494
$warnings.Count | Should -Be 0
9595
}
9696

97+
It "Does not flag true or false being used in ValidateSet" {
98+
# All other read-only automatic variables cannot be used in ValidateSet
99+
# they result in a ParseError. $true and $false are permitted however.
100+
[System.Array] $warnings = Invoke-ScriptAnalyzer -ScriptDefinition 'param([ValidateSet($true,$false)]$MyVar)$MyVar' -ExcludeRule PSReviewUnusedParameter
101+
$warnings.Count | Should -Be 0
102+
}
103+
97104
It "Does not throw a NullReferenceException when using assigning a .Net property to a .Net property (Bug in 1.17.0 - issue 1007)" {
98105
Invoke-ScriptAnalyzer -ScriptDefinition '[foo]::bar = [baz]::qux' -ErrorAction Stop
99106
}

0 commit comments

Comments
 (0)