Skip to content

Commit 1761cf0

Browse files
PoshAJPoshAJ
PoshAJ
authored and
PoshAJ
committed
Add Evaluation for foreach Assignment
1 parent e36d82c commit 1761cf0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Rules/AvoidAssignmentToAutomaticVariable.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,31 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
7979
}
8080
}
8181

82+
IEnumerable<Ast> forEachStatementAsts = ast.FindAll(testAst => testAst is ForEachStatementAst, searchNestedScriptBlocks: true);
83+
foreach (ForEachStatementAst forEachStatementAst in forEachStatementAsts)
84+
{
85+
var variableExpressionAst = forEachStatementAst.Variable;
86+
var variableName = variableExpressionAst.VariablePath.UserPath;
87+
if (_readOnlyAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase))
88+
{
89+
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableError, variableName),
90+
variableExpressionAst.Extent, GetName(), DiagnosticSeverity.Error, fileName, variableName);
91+
}
92+
93+
if (_readOnlyAutomaticVariablesIntroducedInVersion6_0.Contains(variableName, StringComparer.OrdinalIgnoreCase))
94+
{
95+
var severity = IsPowerShellVersion6OrGreater() ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
96+
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToReadOnlyAutomaticVariableIntroducedInPowerShell6_0Error, variableName),
97+
variableExpressionAst.Extent, GetName(), severity, fileName, variableName);
98+
}
99+
100+
if (_writableAutomaticVariables.Contains(variableName, StringComparer.OrdinalIgnoreCase))
101+
{
102+
yield return new DiagnosticRecord(DiagnosticRecordHelper.FormatError(Strings.AvoidAssignmentToWritableAutomaticVariableError, variableName),
103+
variableExpressionAst.Extent, GetName(), DiagnosticSeverity.Warning, fileName, variableName);
104+
}
105+
}
106+
82107
IEnumerable<Ast> parameterAsts = ast.FindAll(testAst => testAst is ParameterAst, searchNestedScriptBlocks: true);
83108
foreach (ParameterAst parameterAst in parameterAsts)
84109
{

0 commit comments

Comments
 (0)