-
Notifications
You must be signed in to change notification settings - Fork 410
Add new AvoidDynamicallyCreatingVariableNames rule #2178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iRon7
wants to merge
10
commits into
PowerShell:main
Choose a base branch
from
iRon7:#1706-AvoidDynamicVariableNames2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+294
−0
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0e873c2
1st commit
iRon7 b4aa1a7
Avoid dynamic variable names rule implementation and tests
iRon7 065c07e
Removed `using System.Linq;` and added some tests
iRon7 ce37bb8
Covering Liam's feedback
iRon7 8a7bbb0
Update docs/Rules/AvoidDynamicallyCreatingVariableNames.md
iRon7 ba0f9a1
Update docs/Rules/AvoidDynamicallyCreatingVariableNames.md
iRon7 680a3cc
Update Rules/Strings.resx
iRon7 b7b7f19
Corrected alphabetical order of rules in README.md
iRon7 ae989fd
Corrected $ruleMessage in Test
iRon7 6fe86a9
Changed newVariableAst.Parent.Extent to newVariableAst.Extent
iRon7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.Linq; | ||
| using System.Management.Automation.Language; | ||
|
|
||
| #if !CORECLR | ||
| using System.ComponentModel.Composition; | ||
| #endif | ||
|
|
||
| namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules | ||
| { | ||
| #if !CORECLR | ||
| [Export(typeof(IScriptRule))] | ||
| #endif | ||
|
|
||
| /// <summary> | ||
| /// Rule that informs the user when they create variables with dynamic names in the general variable scope. | ||
| /// This might lead to conflicts with other variables. | ||
| /// </summary> | ||
| public class AvoidDynamicallyCreatingVariableNames : IScriptRule | ||
| { | ||
| /// <summary> | ||
| /// Analyzes the PowerShell AST for uses of "New-Variable" command with a dynamic name argument. | ||
| /// </summary> | ||
| /// <param name="ast">The PowerShell Abstract Syntax Tree to analyze.</param> | ||
| /// <param name="fileName">The name of the file being analyzed (for diagnostic reporting).</param> | ||
| /// <returns>A collection of diagnostic records for each violation.</returns> | ||
|
|
||
| readonly HashSet<string> cmdList = new HashSet<string>(Helper.Instance.CmdletNameAndAliases("New-Variable"), StringComparer.OrdinalIgnoreCase); | ||
| public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName) | ||
| { | ||
| if (ast == null) throw new ArgumentNullException(Strings.NullAstErrorMessage); | ||
|
|
||
| // Find all "New-Variable" commands in the Ast | ||
| IEnumerable<CommandAst> newVariableAsts = ast.FindAll(testAst => | ||
| testAst is CommandAst cmdAst && | ||
| cmdList.Contains(cmdAst.GetCommandName()), | ||
| true | ||
| ).Cast<CommandAst>(); | ||
|
|
||
| foreach (CommandAst newVariableAst in newVariableAsts) | ||
| { | ||
| // Use StaticParameterBinder to reliably get parameter values | ||
| var bindingResult = StaticParameterBinder.BindCommand(newVariableAst, true); | ||
| if (!bindingResult.BoundParameters.ContainsKey("Name")) { continue; } | ||
| var nameBindingResult = bindingResult.BoundParameters["Name"]; | ||
| // Dynamic parameters return null for the ConstantValue property | ||
| if (nameBindingResult.ConstantValue != null) { continue; } | ||
| string variableName = nameBindingResult.Value.ToString(); | ||
| if (variableName.StartsWith("\"") && variableName.EndsWith("\"")) | ||
| { | ||
| variableName = variableName.Substring(1, variableName.Length - 2); | ||
| } | ||
| yield return new DiagnosticRecord( | ||
| string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.AvoidDynamicallyCreatingVariableNamesError, | ||
| variableName), | ||
| newVariableAst.Extent, | ||
| GetName(), | ||
| DiagnosticSeverity.Information, | ||
| fileName, | ||
| variableName | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| public string GetCommonName() => Strings.AvoidDynamicallyCreatingVariableNamesCommonName; | ||
|
|
||
| public string GetDescription() => Strings.AvoidDynamicallyCreatingVariableNamesDescription; | ||
|
|
||
| public string GetName() => string.Format( | ||
| CultureInfo.CurrentCulture, | ||
| Strings.NameSpaceFormat, | ||
| GetSourceName(), | ||
| Strings.AvoidDynamicallyCreatingVariableNamesName); | ||
|
|
||
| public RuleSeverity GetSeverity() => RuleSeverity.Information; | ||
|
|
||
| public string GetSourceName() => Strings.SourceName; | ||
|
|
||
| public SourceType GetSourceType() => SourceType.Builtin; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
Tests/Rules/AvoidDynamicallyCreatingVariableNames.tests.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. | ||
|
|
||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'False positive')] | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingCmdletAliases', 'nv', Justification = 'For test purposes')] | ||
| param() | ||
|
|
||
| BeforeAll { | ||
| $ruleName = "PSAvoidDynamicallyCreatingVariableNames" | ||
| $ruleMessage = "'{0}' is a dynamic variable name. Please avoid creating variables with a dynamic name" | ||
| } | ||
|
|
||
| Describe "AvoidDynamicallyCreatingVariableNames" { | ||
| Context "Violates" { | ||
| It "Basic dynamic variable name" { | ||
| $scriptDefinition = { New-Variable -Name $Test }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {New-Variable -Name $Test}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f '$Test') | ||
| } | ||
|
|
||
| It "Using alias" { | ||
| $scriptDefinition = { nv -Name $Test }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {nv -Name $Test}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f '$Test') | ||
| } | ||
|
|
||
| It "Using uppercase" { | ||
| $scriptDefinition = { NEW-VARIABLE -Name $Test }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {NEW-VARIABLE -Name $Test}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f '$Test') | ||
| } | ||
|
|
||
| It "Common dynamic variable iteration" { | ||
| $scriptDefinition = { | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| New-Variable -Name "My$_" -Value ($i++) | ||
| } | ||
| $MyTwo # returns 2 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {New-Variable -Name "My$_" -Value ($i++)}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f 'My$_') | ||
| } | ||
|
|
||
| It "Unquoted positional binding" { | ||
| $scriptDefinition = { | ||
| $myVarName = 'foo' | ||
| New-Variable $myVarName | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {New-Variable $myVarName}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f '$myVarName') | ||
| } | ||
|
|
||
| It "Quoted positional binding" { | ||
| $scriptDefinition = { | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| New-Variable "My$_" ($i++) | ||
| } | ||
| $MyTwo # returns 2 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations.Count | Should -Be 1 | ||
| $violations.Severity | Should -Be Information | ||
| $violations.Extent.Text | Should -Be {New-Variable "My$_" ($i++)}.ToString() | ||
| $violations.Message | Should -Be ($ruleMessage -f 'My$_') | ||
| } | ||
| } | ||
|
|
||
| Context "Compliant" { | ||
| It "Common hash table population" { | ||
| $scriptDefinition = { | ||
| $My = @{} | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| $My[$_] = $i++ | ||
| } | ||
| $My.Two # returns 2 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "Scoped hash table population" { | ||
| $scriptDefinition = { | ||
| New-Variable -Name My -Value @{} -Option ReadOnly -Scope Script | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| $Script:My[$_] = $i++ | ||
| } | ||
| $Script:My.Two # returns 2 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
|
|
||
| It "Verbatim (single quoted) name with dollar sign" { | ||
| $scriptDefinition = { | ||
| New-Variable -Name '$Sign1' | ||
| New-Variable -Name '$Sign2' -Value 'Dollar' | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
| } | ||
|
|
||
| Context "Suppressed" { | ||
| It "Basic dynamic variable name" { | ||
| $scriptDefinition = { | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidDynamicallyCreatingVariableNames', '$Test', Justification = 'Test')] | ||
| Param() | ||
| New-Variable -Name $Test | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
| It "Common dynamic variable iteration" { | ||
| $scriptDefinition = { | ||
| [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidDynamicallyCreatingVariableNames', 'My$_', Justification = 'Test')] | ||
| Param() | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| New-Variable -Name "My$_" -Value ($i++) | ||
| } | ||
| $MyTwo # returns 2 | ||
| }.ToString() | ||
| $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName) | ||
| $violations | Should -BeNullOrEmpty | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| --- | ||
| description: Avoid dynamic variable names, instead use a hash table or similar dictionary type. | ||
| ms.date: 04/21/2026 | ||
| ms.topic: reference | ||
| title: AvoidDynamicallyCreatingVariableNames | ||
| --- | ||
| # AvoidDynamicallyCreatingVariableNames | ||
|
|
||
| **Severity Level: Information** | ||
|
|
||
| ## Description | ||
|
|
||
| Do not create variables with a dynamic name, this might introduce conflicts with | ||
| other variables and is difficult to maintain. | ||
|
|
||
| ## How | ||
|
|
||
| Use a hash table or similar dictionary type to store values with dynamic keys. | ||
|
|
||
| ## Example | ||
|
|
||
| ### Wrong | ||
|
|
||
| ```powershell | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| New-Variable -Name "My$_" -Value ($i++) | ||
| } | ||
| $MyTwo # returns 2 | ||
| ``` | ||
|
|
||
| ### Correct | ||
|
|
||
| ```powershell | ||
| $My = @{} | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| $My[$_] = $i++ | ||
| } | ||
| $My.Two # returns 2 | ||
| ``` | ||
|
|
||
| When a specific scope, option, or visibility is required, put the dictionary (hash table) in that | ||
| scope and apply the appropriate option or visibility. For example, if the values should be read-only and | ||
| available in the script scope, put the _hash table_ in the script scope and make it read-only. | ||
|
|
||
| ```powershell | ||
| New-Variable -Name My -Value @{} -Option ReadOnly -Scope Script | ||
| 'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process { | ||
| $Script:My[$_] = $i++ | ||
| } | ||
| $Script:My.Two # returns 2 | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.