How to add PowerShell linting to projects in Visual Studio Code

Linting tools provide a way for us to automatically analyze source code to find bugs and style problems. Adding these tools to your project will help enforce coding best practices and maintain them as the project grows. In this post we demonstrate how to configure linting for PowerShell code projects in the Visual Studio Code editor using the PSScriptAnalyzer toolset.

Step 1: Add the PowerShell VSCode extension

If you have been working on PowerShell code projects in VSCode, then chances are you may have this extension installed already. This is because VSCode usually prompts you to install the extension when you open PowerShell files. In case you don’t have it installed:

Navigate to the File menu > Preferences > Extensions. In the search box, search for the extension named PowerShell and hit install.

Step 2: Add the script analyzer settings file

PSScriptAnalyzer uses a settings file to describe which rules to enforce in your project. In the root of your project create a new file called ScriptAnalyzerSettings.psd1. The Plaster project on Github has a nice example settings file here, which is a good starting point:

@{
    # Use Severity when you want to limit the generated diagnostic records to a
    # subset of: Error, Warning and Information.
    # Uncomment the following line if you only want Errors and Warnings but
    # not Information diagnostic records.
    Severity = @('Error','Warning')

    # Use IncludeRules when you want to run only a subset of the default rule set.
    #IncludeRules = @('PSAvoidDefaultValueSwitchParameter',
    #                 'PSMissingModuleManifestField',
    #                 'PSReservedCmdletChar',
    #                 'PSReservedParams',
    #                 'PSShouldProcess',
    #                 'PSUseApprovedVerbs',
    #                 'PSUseDeclaredVarsMoreThanAssigments')

    # Use ExcludeRules when you want to run most of the default set of rules except
    # for a few rules you wish to "exclude".  Note: if a rule is in both IncludeRules
    # and ExcludeRules, the rule will be excluded.
    ExcludeRules = @(
        'PSAvoidUsingWriteHost',
        'PSMissingModuleManifestField'
    )

    # You can use the following entry to supply parameters to rules that take parameters.
    # For instance, the PSAvoidUsingCmdletAliases rule takes a whitelist for aliases you
    # want to allow.
    #Rules = @{
    #    Do not flag 'cd' alias.
    #    PSAvoidUsingCmdletAliases = @{Whitelist = @('cd')}

    #    Check if your script uses cmdlets that are compatible on PowerShell Core,
    #    version 6.0.0-alpha, on Linux.
    #    PSUseCompatibleCmdlets = @{Compatibility = @("core-6.0.0-alpha-linux")}
    #}
}

Ruleset documentation

A complete list of all the rules can be found in the PSScriptAnalyzer repository here. Clicking on each rule in the list will lead you directly to the documentation for that rule which includes the pass/fail examples and configuration options (if applicable).

Step 3: Update the VSCode workspace settings.

PSScriptAnalyzer is bundled with the PowerShell extension. In order to have automatic linting with our settings we need to update the PowerShell extension settings to specify the location of the script analyzer settings file.

Go back to the VSCode extensions panel and find the PowerShell extension. Click manage (gear icon), then configure extension settings. Under the workspace settings find: PowerShell › Script Analysis: Settings Path. Add the name of settings file here (PSScriptAnalyzerSettings.psd1).

If haven’t already created any workspace scoped settings, then you will see a new file in the root called .vscode\settings.json. In that settings file the powershell.scriptAnalysis.settingsPath setting should now be present.

If you check the settings.json file and the script analyzer settings file into source control with the rest of your code, then anyone else who pulls down the repository will automatically receive the linting if they have the PowerShell extension installed.

Note: To have linting rules enforced as a part of a continuous integration (CI) pipeline (instead of just locally), you can import the PSScriptAnalyzer toolset and invoke the analysis commands directly (by calling Invoke-ScriptAnalyzer) within your build steps.

Verification

If all 3 steps were performed correctly then PSScriptAnalyzer should automatically start detecting errors when you open up PowerShell files (no need to restart VSCode). These errors will show up in the Problems window in VSCode as seen below:

Problems window in VSCode.

Handling rule suppression

There may be some cases where you need to suppress a linting rule for a particular cmdlet/function file. There is an attribute in .NET for suppressing code analysis rules called SuppressMessageAttribute and PSScriptAnalyzer supports this too. Suppression examples can be found here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s