PowerShell Inside All articles
PowerShell Fundamentals

Reading PowerShell's Family Tree: Building Custom AST Rules That Go Beyond PSScriptAnalyzer

PowerShell Inside
Reading PowerShell's Family Tree: Building Custom AST Rules That Go Beyond PSScriptAnalyzer

Photo: Wikinaut, CC0, via Wikimedia Commons

Every team hits the same wall with PSScriptAnalyzer. The shipped rules catch the well-known stuff — Invoke-Expression with a variable, unapproved verbs, $null on the left side of a comparison — and then they stop. They have no idea that D:\Apps\Billing\prod is off-limits outside a deployment script, that ConvertTo-SecureString -AsPlainText -Force is effectively banned in your shop, or that nobody may call Set-ADAccountPassword without a change ticket in the comment-based help.

That gap is where custom rules earn their keep. And the good news: you don't have to write a parser. PowerShell already ships one, and it will hand you a complete abstract syntax tree (AST) for any script you feed it.

The parser is already in the box

Before you touch PSScriptAnalyzer, look at what the engine gives you for free:

$tokens = $null
$errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile(
    'C:\Scripts\Deploy-App.ps1', [ref]$tokens, [ref]$errors)

$ast.GetType().FullName   # System.Management.Automation.Language.ScriptBlockAst

Everything in that tree is an Ast subclass: CommandAst for a pipeline element that invokes a command, StringConstantExpressionAst for a quoted literal, AssignmentStatementAst for $x = ..., InvokeMemberExpressionAst for a method call like $wc.DownloadString(...). Two traversal methods do most of the work:

That second argument matters more than people expect. Pass $false and you'll silently skip everything inside a function body — the single most common reason a custom rule "doesn't fire" in review.

Designing around a real hazard

Let's take three rules most shops actually want:

  1. No production paths in string literals. Deploy scripts take a parameter; they don't hard-code \\prod- UNC roots.
  2. No banned cmdlets. Maybe Invoke-Expression, maybe Set-MpPreference, maybe your own Reset-ProdDatabase.
  3. No plaintext credential conversion. Flag ConvertTo-SecureString calls that use -AsPlainText.

Each maps cleanly to an AST node type, which is the whole trick. Learn the node, and the rule writes itself.

Writing the rule module

A custom rule is a class implementing IScriptRule, exported from a .psm1. Save this as rules/TeamRules.psm1:

using namespace System.Management.Automation.Language
using namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic

[Export(typeof(IScriptRule))]
class AvoidProductionPath : IScriptRule {
    [System.Collections.Generic.IEnumerable[DiagnosticRecord]] GetDiagnosticRecords([ScriptBlockAst]$ast) {
        $results = [System.Collections.Generic.List[DiagnosticRecord]]::new()
        $pattern = '\\[\\/](prod|production)[\\/]'

        $nodes = $ast.FindAll({
            param($node)
            $node -is [StringConstantExpressionAst] -or $node -is [ExpandableStringExpressionAst]
        }, $true)

        foreach ($node in $nodes) {
            if ($node.Value -match $pattern) {
                $results.Add([DiagnosticRecord]::new(
                    $this,
                    "Hard-coded production path '$($node.Value)'. Pass it as a parameter instead.",
                    [RuleSeverity]::Error,
                    $node.Extent,
                    $null))
            }
        }
        return $results
    }

    [string] GetName()        { return 'AvoidProductionPath' }
    [string] GetCommonName()  { return 'Avoid hard-coded production paths' }
    [string] GetDescription() { return 'Production filesystem and UNC paths must be supplied via parameter or configuration lookup.' }
}

[Export(typeof(IScriptRule))]
class BannedCommand : IScriptRule {
    static [string[]] $Banned = @('Invoke-Expression', 'Set-MpPreference', 'Reset-ProdDatabase')

    [System.Collections.Generic.IEnumerable[DiagnosticRecord]] GetDiagnosticRecords([ScriptBlockAst]$ast) {
        $results = [System.Collections.Generic.List[DiagnosticRecord]]::new()
        foreach ($cmd in $ast.FindAll({ param($n) $n -is [CommandAst] }, $true)) {
            $name = $cmd.GetCommandName()
            if ($name -and [BannedCommand]::Banned -contains $name) {
                $results.Add([DiagnosticRecord]::new($this,
                    "'$name' is not permitted in this repository. Open a platform review instead.",
                    [RuleSeverity]::Error, $cmd.Extent, $null))
            }
        }
        return $results
    }

    [string] GetName()        { return 'BannedCommand' }
    [string] GetCommonName()  { return 'Banned command usage' }
    [string] GetDescription() { return 'Blocks commands that require platform review before use.' }
}

Note the Extent you attach to every diagnostic — that's what produces the squiggly line in VS Code and the file/line coordinates in CI output. Without it, your finding is a complaint with no address.

Run it against a sample:

Invoke-ScriptAnalyzer -Path .\samples\Deploy-App.ps1 `
    -CustomRulePath .\rules\TeamRules.psm1 `
    | Format-Table RuleName, Severity, Line, Message -AutoSize

Keeping false positives from killing adoption

A rule that cries wolf gets disabled by the second sprint. Two escape hatches keep it honest. First, SuppressMessage in the script — PSScriptAnalyzer honors it for custom rules:

function Invoke-ProdRestart {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('AvoidProductionPath', '',
        Justification = 'Deploy agent only. Reviewed in CHG004211.')]
    param()
}

Second, drive thresholds and allow-lists through -Settings instead of editing code:

{
  "Rules": {
    "PSAvoidUsingWriteHost": { "Enable": false }
  },
  "IncludeRules": ["AvoidProductionPath", "BannedCommand"]
}

Keep the allow-lists in a settings file so the platform team can loosen a rule for one app without touching the rule module the whole org shares.

Prove the rule with Pester

Rules are code, and untested code drifts. A three-line Pester test catches nearly every regression:

Describe 'AvoidProductionPath' {
    It 'flags a prod UNC literal' {
        $r = Invoke-ScriptAnalyzer -Path "$PSScriptRoot\fixtures\bad.ps1" `
            -CustomRulePath "$PSScriptRoot\..\rules\TeamRules.psm1"
        $r | Where-Object RuleName -eq 'AvoidProductionPath' | Should -Not -BeNullOrEmpty
    }
    It 'leaves parameterized paths alone' {
        $r = Invoke-ScriptAnalyzer -Path "$PSScriptRoot\fixtures\good.ps1" `
            -CustomRulePath "$PSScriptRoot\..\rules\TeamRules.psm1"
        $r | Where-Object RuleName -eq 'AvoidProductionPath' | Should -BeNullOrEmpty
    }
}

Ship at least one passing fixture and one failing fixture per rule. The negative test is the one that saves you.

Wire it into CI once

In GitHub Actions, Azure Pipelines, or Jenkins, the gate is the same shape: install the module, invoke, fail on error severity.

$findings = Invoke-ScriptAnalyzer -Path .\src -Recurse `
    -CustomRulePath .\rules\TeamRules.psm1 -Severity Error
if ($findings) { $findings | Format-Table -Wrap; exit 1 }

Pin PSScriptAnalyzer to an exact version in your build image — the Generic namespace has moved across major versions, and an unpinned runner will break your rule module at the worst possible moment.

The real payoff isn't the three rules above. It's that your review checklist stops living in a senior engineer's head and starts living in a testable tree walk that runs on every pull request — including the ones submitted at 4:45 on a Friday.

All Articles

Related Articles

Objects in Flight: Rewiring Your Mental Model of the PowerShell Pipeline

Objects in Flight: Rewiring Your Mental Model of the PowerShell Pipeline

$Error Is a Crime Scene, Not a Report: A Structured Failure Contract for Production PowerShell

$Error Is a Crime Scene, Not a Report: A Structured Failure Contract for Production PowerShell

4104 at Scale: Turning PowerShell Script Block Logging Into Telemetry Your SOC Will Actually Keep

4104 at Scale: Turning PowerShell Script Block Logging Into Telemetry Your SOC Will Actually Keep