PowerShell / PowerShell/PSScriptAnalyzer

Suggestion for new rule - Ensure that variables used in a function is always declared in the local scope

Open
#632 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

In order to reduce the number of hard to debug errors, we run our PowerShell scripts with Set-StrictMode -Version Latest. This lets us catch issues where we e.g. have misspelled a variable name (or forgot to assign it before using it) during runtime. But it would be immensely useful to catch these kinds of errors before we run the scripts, e.g. during an automated build.

We have deployment scripts that run for quite a long time (several hours), and silly misspelled variable names or misplaced variable assignments then costs quite a bit of development time. Catching these errors early would be immensely useful.

Example of something that should cause an error:

function Get-Foobar()
{
    if ($b + 2 -gt 5)
    {
        return $b
    }

    return 5
}

This would be OK:

function Get-Foobar($b)
{
    if ($b + 2 -gt 5)
    {
        return $b
    }

    return 5
}

As would this:

function Get-Foobar()
{
    $b = 123;
    if ($b + 2 -gt 5)
    {
        return $b
    }

    return 5
}

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 from the two PowerShell examples in the issue and inspect the repository's existing analyzer rules and tests to determine where a new rule belongs. Define how parameters, assignments, and variable references should be handled; done means the undeclared-variable example is reported while both valid examples pass, with coverage for the chosen behavior.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.