Skip to content

Fix FixPSUseDeclaredVarsMoreThanAssignments to also detect variables that are strongly typed #837

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Rules/UseDeclaredVarsMoreThanAssignments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,17 @@ private IEnumerable<DiagnosticRecord> AnalyzeScriptBlockAst(ScriptBlockAst scrip
// Only checks for the case where lhs is a variable. Ignore things like $foo.property
VariableExpressionAst assignmentVarAst = assignmentAst.Left as VariableExpressionAst;

if (assignmentVarAst == null)
{
// If the variable is declared in a strongly typed way, e.g. [string]$s = 'foo' then the type is ConvertExpressionAst.
// Therefore we need to the VariableExpressionAst from its Child property.
var assignmentVarAstAsConvertExpressionAst = assignmentAst.Left as ConvertExpressionAst;
if (assignmentVarAstAsConvertExpressionAst != null && assignmentVarAstAsConvertExpressionAst.Child != null)
{
assignmentVarAst = assignmentVarAstAsConvertExpressionAst.Child as VariableExpressionAst;
}
}

if (assignmentVarAst != null)
{
// Ignore if variable is global or environment variable or scope is function
Expand Down
6 changes: 6 additions & 0 deletions Tests/Rules/UseDeclaredVarsMoreThanAssignments.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ function MyFunc2() {
Should Be 1
}

It "flags strongly typed variables" {
Invoke-ScriptAnalyzer -ScriptDefinition '[string]$s=''mystring''' -IncludeRule $violationName | `
Get-Count | `
Should Be 1
}

It "does not flag `$InformationPreference variable" {
Invoke-ScriptAnalyzer -ScriptDefinition '$InformationPreference=Stop' -IncludeRule $violationName | `
Get-Count | `
Expand Down