Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aldrichtr/083d1c02e90625ff925ae8b1d8870be4 to your computer and use it in GitHub Desktop.
Save aldrichtr/083d1c02e90625ff925ae8b1d8870be4 to your computer and use it in GitHub Desktop.
PowerShell 7 Pre Commit Hook using PSScriptAnalyzer

Summary

A PowerShell 7 pre commit hook to lint your PowerShell code using the PSScriptAnalyzer module.

Prerequisites

  1. PowerShell 7
  2. Git
  3. PSScriptAnalyzer module

Snippet

#!/usr/bin/env pwsh
Import-Module -Name "PSScriptAnalyzer"

$DiffNames = git --no-pager diff --name-only --staged --line-prefix="$(git rev-parse --show-toplevel)/"
$Results = @()

foreach ($DiffName in $DiffNames) {
    Write-Output -InputObject "Analysing ""$($DiffName)"""
    $Output = Invoke-ScriptAnalyzer -Path $DiffName
    $Results += $Output
}

if ($Results.Count -gt 0) {
    Write-Warning -Message "PSScriptAnalyzer identified one or more files with linting errors. Commit aborted. Fix them before committing or use 'git commit --no-verify' to bypass this check."
    foreach ($Result in $Results) {
        Write-Error -Message "$($Result.ScriptName) - Line $($Result.Line) - $($Result.Message)"
    }
    exit 1
}

Usage

Linux

  1. Paste the PowerShell code snippet above into .git/hooks/pre-commit

  2. Make your .git/hooks/pre-commit executable:

    chmod +x .git/hooks/pre-commit

Windows

  1. Paste the PowerShell code snippet above into .git/hooks/pre-commit.ps1

  2. Paste the code snippet below into .git/hooks/pre-commit:

    #!/bin/sh
    pwsh -File "$(git rev-parse --show-toplevel)\.git\hooks\pre-commit.ps1"

Enjoy! ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment