PowerShell / PowerShell/PSScriptAnalyzer

Add rule for unused namespaces

Open
#2,026 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue - New Rule Up-for-Grabs
Dominant language
C#
Stars
2.2k
Forks
414
Avg merge
13h 1m
Merged PRs (30d)
2

Description

Summary of the new feature
It would be nice with a rule to find and remove unused using namespace statements similar to what you can do in C# in editors like VS.
Cleaning up unused namespaces can slightly improve type resolution performance and of course it makes scripts more neat and clean.

Proposed technical implementation details (optional)
Use FindAll on the root AST to find all Asts of the following types: TypeExpressionAst, TypeConstraintAst, AttributeAst and CommandAst where the command name is New-Object and try to resolve the specified TypeNames with GetReflectionType. Compare the written typename with the resolved typename and see if part of the namespace is missing, and if so if that part is listed in the list of namespaces. If it is then that namespace is in use and should stay.

For New-Object we can't use GetReflectionType so I'm not sure how to handle that. Type accelerators and in the future type/namespace aliases should probably also be taken into consideration.

What is the latest version of PSScriptAnalyzer at the point of writing

1.22.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the root AST and the FindAll searches for TypeExpressionAst, TypeConstraintAst, AttributeAst, and New-Object CommandAst nodes described in the issue. Determine how type names are resolved and how New-Object, type accelerators, and possible aliases should be handled. Done means the analyzer can identify unused using namespace statements without removing namespaces that are referenced.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, powershell
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.