Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
c34eb23
Implemented the AvoidUsingArrayList rule to warn when the ArrayList c…
iRon7 Apr 14, 2026
ba1167d
Testing-Commit-CSpell-issue
iRon7 Apr 16, 2026
77384e1
Apply suggestion from @liamjpeters
iRon7 Apr 16, 2026
77d1e6d
Update docs/Rules/AvoidUsingArrayList.md
iRon7 Apr 16, 2026
d9b88a8
Updated rule help
iRon7 Apr 16, 2026
1eb92e9
Merge branch '#2147AvoidArrayList' of https://github.com/iRon7/PSScri…
iRon7 Apr 16, 2026
c0aa82b
Changed "unintentionally"
iRon7 Apr 16, 2026
7bc3dfa
Update Rules/AvoidUsingArrayList.cs
iRon7 Apr 16, 2026
b35becb
Update Tests/Rules/AvoidUsingArrayList.tests.ps1
iRon7 Apr 16, 2026
9ed1355
ArrayListName could be null
iRon7 Apr 16, 2026
e1362e6
Resolved camelCase
iRon7 Apr 16, 2026
b80f01c
Remove ComponentModel namespace
iRon7 Apr 16, 2026
f913b1f
Fixed tests
iRon7 Apr 16, 2026
b3a5c3c
Updated Tests
iRon7 Apr 16, 2026
8aefe4c
fixed and tested empty (dynamic) BoundParameter
iRon7 Apr 16, 2026
ad49041
Robuster Pester tests
iRon7 Apr 17, 2026
4bc41e9
Configurable (enable by default)
iRon7 Apr 18, 2026
fb27627
Fixed ConstantValue null check test and rule
iRon7 Apr 21, 2026
5a66672
Merge branch 'main' into #2147AvoidArrayList
iRon7 May 5, 2026
973d2e7
Better UsingStatements handling and disable AvoidUsingArrayList by de…
iRon7 May 6, 2026
14ed9f5
`[ArrayList]::new()` without a `using namespace System.Collections`
iRon7 May 6, 2026
2a46b7f
Potential fix for pull request finding
iRon7 May 11, 2026
0646b3d
Resolve Copilot suggestions and resolved `Method not found: ScriptBlo…
iRon7 May 11, 2026
49a1a55
Merge branch 'main' into #2147AvoidArrayList
iRon7 May 17, 2026
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
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
"**/bower_components": true,
"/PSCompatibilityCollector/profiles": true,
"/PSCompatibilityCollector/optional_profiles": true
}
},
"cSpell.words": [
Comment thread
iRon7 marked this conversation as resolved.
Outdated
"CORECLR"
]
}
144 changes: 144 additions & 0 deletions Rules/AvoidUsingArrayList.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// 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.Management.Automation.Language;
using System.Text.RegularExpressions;
using System.ComponentModel;
Comment thread
iRon7 marked this conversation as resolved.
Outdated


#if !CORECLR
using System.ComponentModel.Composition;
#endif

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules
{
#if !CORECLR
[Export(typeof(IScriptRule))]
#endif

/// <summary>
/// Rule that warns when the ArrayList class is used in a PowerShell script.
/// </summary>
public class AvoidUsingArrayListAsFunctionNames : IScriptRule
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The class name has a little copy-pasta 😊

Also, I think this should be a configurable rule, disabled by default.

Instead of directly implementing IScriptRule, implement ConfigurableRule. See AvoidExclaimOperator as an example.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I change this, I notice that there are quite some inherited methods to be implemented.
Before going into this direction, can you argue why you think this rule should be disabled by default?
Or even configurable?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will start by saying that this is just my own personal opinion. I'm not a part of Microsoft or the PSScriptAnalyzer team - just an interested community member. @bergmeister is the community maintainer and will have their own take 😊.

I've submitted a few PRs to the project and added a few new rules over the years, and this is just from my own experience from going through PR review.

  • ArrayList is extremely common in existing PowerShell scripts. Enabling this by default would flood users with warnings on legacy code they may not own or want to refactor. PSSA is used commonly in CICD pipelines - introducing a bunch of new warnings (which you would usually treat as a build failure) would not be popular - maybe even with the PowerShell team themselves.

  • Replacing ArrayList with List[Object] changes behavior (no return value from .Add(). Code that relied on the index return from ArrayList.Add() - even accidentally via pipeline pollution - would break. Admittedly, 99.9% of the time, you don't want the collection size returned when you're appending to it - but there's always someone!

  • Making it opt-in lets people set it up for new code, or work through their legacy code base in their own time more easily.

As to why ConfigurableRule...

Only ConfigurableRule can be truly disabled by default. While it's true that all rules, including IScriptRule rules, can be stopped from participating in analysis by using -ExcludeRule as a cmdlet parameter or in a settings files - that is explicit opt-out. Any analysis with no settings file or include/exclude parameter will run all IScriptRule rules.

If you're interested, here's where the enabled rules are checked. If it's not a configurable rule, it's considered enabled.

private static bool IsRuleEnabled(IRule rule)
{
var configurableRule = rule as ConfigurableRule;
return configurableRule == null || configurableRule.Enable;
}

The Refactor should be fairly simple. ConfigurableRule is an abstract class which itself implements IScriptRule, so when you change from implementing IScriptRule to ConfigurableRule you will just need to mark your existing methods as override - it's not a wholesale rewrite. So for instance:

- public string GetCommonName() => Strings.AvoidUsingArrayListCommonName;
+ public override string GetCommonName() => Strings.AvoidUsingArrayListCommonName;

That should be it within the class. You would also need to update your tests to enable your rule for testing.

@{ Rules = @{ PSAvoidUsingArrayList = @{ Enable = $true } } }

As I said - just my opinion 🙂

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for you thoughts, I will take it in consideration.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have made the rule configurable.
But enabled it by default as I think it will prevents the pipeline pollution gotcha.

{

/// <summary>
/// Analyzes the PowerShell AST for uses of the ArrayList class.
/// </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>

public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
{
if (ast == null) { throw new ArgumentNullException(Strings.NullAstErrorMessage); }
Comment thread
iRon7 marked this conversation as resolved.
Outdated

// If there is an using statement for the Collections namespace, check for the full typename.
// Otherwise also check for the bare ArrayList name.
Regex ArrayListName = null;
Comment thread
iRon7 marked this conversation as resolved.
Outdated
var sbAst = ast as ScriptBlockAst;
foreach (UsingStatementAst usingAst in sbAst.UsingStatements)
{
if (
usingAst.UsingStatementKind == UsingStatementKind.Namespace &&
(
usingAst.Name.Value.Equals("Collections", StringComparison.OrdinalIgnoreCase) ||
usingAst.Name.Value.Equals("System.Collections", StringComparison.OrdinalIgnoreCase)
)
)
{
ArrayListName = new Regex(@"^((System\.)?Collections\.)?ArrayList$", RegexOptions.IgnoreCase);
break;
}
}
if (ArrayListName == null) { ArrayListName = new Regex(@"^(System\.)?Collections\.ArrayList", RegexOptions.IgnoreCase); }
Comment thread
iRon7 marked this conversation as resolved.
Outdated

// Find all type initializers that create a new instance of the ArrayList class.
IEnumerable<Ast> typeAsts = ast.FindAll(testAst =>
(
testAst is ConvertExpressionAst convertAst &&
convertAst.StaticType != null &&
convertAst.StaticType.FullName == "System.Collections.ArrayList"
) ||
(
testAst is TypeExpressionAst typeAst &&
typeAst.TypeName != null &&
ArrayListName.IsMatch(typeAst.TypeName.Name) &&
typeAst.Parent is InvokeMemberExpressionAst parentAst &&
parentAst.Member != null &&
parentAst.Member is StringConstantExpressionAst memberAst &&
memberAst.Value.Equals("new", StringComparison.OrdinalIgnoreCase)
),
true
);

foreach (Ast typeAst in typeAsts)
{
yield return new DiagnosticRecord(
string.Format(
CultureInfo.CurrentCulture,
Strings.AvoidUsingArrayListError,
typeAst.Parent.Extent.Text),
typeAst.Extent,
GetName(),
DiagnosticSeverity.Warning,
fileName
);
}

// Find all New-Object cmdlets that create a new instance of the ArrayList class.
var newObjectCommands = ast.FindAll(testAst =>
testAst is CommandAst cmdAst &&
cmdAst.GetCommandName() != null &&
cmdAst.GetCommandName().Equals("New-Object", StringComparison.OrdinalIgnoreCase),
true);

foreach (CommandAst cmd in newObjectCommands)
{
// Use StaticParameterBinder to reliably get parameter values
var bindingResult = StaticParameterBinder.BindCommand(cmd, true);

// Check for -TypeName parameter
if (
bindingResult.BoundParameters.ContainsKey("TypeName") &&
ArrayListName.IsMatch(bindingResult.BoundParameters["TypeName"].ConstantValue as string)
Comment thread
iRon7 marked this conversation as resolved.
Outdated
)
Comment thread
iRon7 marked this conversation as resolved.
{
yield return new DiagnosticRecord(
string.Format(
CultureInfo.CurrentCulture,
Strings.AvoidUsingArrayListError,
cmd.Extent.Text),
bindingResult.BoundParameters["TypeName"].Value.Extent,
GetName(),
DiagnosticSeverity.Warning,
Comment thread
bergmeister marked this conversation as resolved.
fileName
);
}

}


}

public string GetCommonName() => Strings.AvoidUsingArrayListCommonName;

public string GetDescription() => Strings.AvoidUsingArrayListDescription;

public string GetName() => string.Format(
CultureInfo.CurrentCulture,
Strings.NameSpaceFormat,
GetSourceName(),
Strings.AvoidUsingArrayListName);

public RuleSeverity GetSeverity() => RuleSeverity.Warning;

public string GetSourceName() => Strings.SourceName;

public SourceType GetSourceType() => SourceType.Builtin;
}
}
12 changes: 12 additions & 0 deletions Rules/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,18 @@
</data>
<data name="AvoidSemicolonsAsLineTerminatorsError" xml:space="preserve">
<value>Line ends with a semicolon</value>
</data>
<data name="AvoidUsingArrayListCommonName" xml:space="preserve">
<value>Avoid using the ArrayList class</value>
</data>
<data name="AvoidUsingArrayListDescription" xml:space="preserve">
<value>Avoid using the ArrayList class in PowerShell scripts. Consider using generic collections or fixed arrays instead.</value>
</data>
<data name="AvoidUsingArrayListName" xml:space="preserve">
<value>AvoidUsingArrayList</value>
</data>
<data name="AvoidUsingArrayListError" xml:space="preserve">
<value>The ArrayList class is used in '{0}'. Consider using a generic collection or a fixed array instead.</value>
</data>
<data name="PlaceOpenBraceName" xml:space="preserve">
<value>PlaceOpenBrace</value>
Expand Down
18 changes: 18 additions & 0 deletions Tests/Rules/AvoidUsingArrayList.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using namespace system.collections

# Using New-Object
$List = New-Object ArrayList
$List = New-Object 'ArrayList'
$List = New-Object "ArrayList"
$List = New-Object -Type ArrayList
$List = New-Object -TypeName ArrayLIST
$List = New-Object Collections.ArrayList
$List = New-Object System.Collections.ArrayList

# Using type initializer
$List = [ArrayList](1,2,3)
$List = [ArrayLIST]@(1,2,3)
$List = [ArrayList]::new()
$List = [Collections.ArrayList]::New()
$List = [System.Collections.ArrayList]::new()
1..3 | ForEach-Object { $null = $List.Add($_) }
26 changes: 26 additions & 0 deletions Tests/Rules/AvoidUsingArrayList.tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

BeforeAll {
$ruleName = "PSAvoidArrayList"
$ruleMessage = "The ArrayList class is used in '*'. Consider using a generic collection or a fixed array instead."
}

Describe "AvoidUsingWriteHost" {
Comment thread
iRon7 marked this conversation as resolved.
Outdated
Context "When there are violations" {
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -IncludeRule @($ruleName)
Comment thread
iRon7 marked this conversation as resolved.
Outdated
It "has ArrayList violations" {
$violations.Count | Should -Be 12
}

It "has the correct description message" {
$violations[0].Message | Should -Like $ruleMessage
}
}

Context "When there are no violations" {
It "returns no violations" {
$noViolations.Count | Should -Be 0
}
}
}
19 changes: 19 additions & 0 deletions Tests/Rules/AvoidUsingArrayListNoViolations.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using namespace System.Collections.Generic

# Using a generic List
$List = New-Object List[Object]
1..3 | ForEach-Object { $List.Add($_) } # This will not return anything

$List = [List[Object]]::new()
1..3 | ForEach-Object { $List.Add($_) } # This will not return anything

# Creating a fixed array by using the PowerShell pipeline
$List = 1..3 | ForEach-Object { $_ }

# This should not violate because there isn't a
# `using namespace System.Collections` directive
# and ArrayList could belong to another namespace
$List = New-Object ArrayList
$List = [ArrayList](1,2,3)
$List = [ArrayList]@(1,2,3)
$List = [ArrayList]::new()
47 changes: 47 additions & 0 deletions docs/Rules/AvoidUsingArrayList.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
description: Avoid reserved words as function names
Comment thread
iRon7 marked this conversation as resolved.
Outdated
ms.date: 08/31/2025
Comment thread
iRon7 marked this conversation as resolved.
Outdated
ms.topic: reference
title: AvoidUsingArrayList
---
Comment thread
iRon7 marked this conversation as resolved.
# AvoidUsingArrayList

**Severity Level: Warning**

## Description

Important
Comment thread
iRon7 marked this conversation as resolved.
Outdated

Avoid the ArrayList class for new development.
The `ArrayList` class is a non-generic collection that can hold objects of any type. This is inline with the fact
that PowerShell is a weakly typed language. However, the `ArrayList` class does not provide any explicit type
safety and performance benefits of generic collections. Instead of using an `ArrayList`, consider using either a
[`System.Collections.Generic.List[Object]`](https://learn.microsoft.com/dotnet/api/system.collections.generic.list-1)
class or a fixed PowerShell array. Besides, the `ArrayList.Add` method returns the index of the added element which
often unintendedly pollutes the PowerShell pipeline and therefore might cause unexpected issues.
Comment thread
iRon7 marked this conversation as resolved.
Outdated


## How to Fix

## Example

### Wrong

```powershell
# Using an ArrayList
$List = [System.Collections.ArrayList]::new()
1..3 | ForEach-Object { $List.Add($_) } # Note that this will return the index of the added element
```

### Correct

```powershell
# Using a generic List
$List = [System.Collections.Generic.List[Object]]::new()
1..3 | ForEach-Object { $List.Add($_) } # This will not return anything
```

```PowerShell
Comment thread
iRon7 marked this conversation as resolved.
Outdated
# Creating a fixed array by using the PowerShell pipeline
$List = 1..3 | ForEach-Object { $_ }
```
1 change: 1 addition & 0 deletions docs/Rules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ The PSScriptAnalyzer contains the following rule definitions.
| [AvoidShouldContinueWithoutForce](./AvoidShouldContinueWithoutForce.md) | Warning | Yes | |
| [AvoidTrailingWhitespace](./AvoidTrailingWhitespace.md) | Warning | Yes | |
| [AvoidUsingAllowUnencryptedAuthentication](./AvoidUsingAllowUnencryptedAuthentication.md) | Warning | Yes | |
| [AvoidUsingArrayList](./AvoidUsingArrayList.md) | Warning | Yes | |
Comment thread
iRon7 marked this conversation as resolved.
Outdated
| [AvoidUsingBrokenHashAlgorithms](./AvoidUsingBrokenHashAlgorithms.md) | Warning | Yes | |
| [AvoidUsingCmdletAliases](./AvoidUsingCmdletAliases.md) | Warning | Yes | Yes<sup>2</sup> |
| [AvoidUsingComputerNameHardcoded](./AvoidUsingComputerNameHardcoded.md) | Error | Yes | |
Expand Down
Loading