A PowerShell 7 pre commit hook to lint your PowerShell code using the PSScriptAnalyzer module.
- PowerShell 7
- Git
- PSScriptAnalyzer module
#!/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
}
-
Paste the PowerShell code snippet above into
.git/hooks/pre-commit
-
Make your
.git/hooks/pre-commit
executable:chmod +x .git/hooks/pre-commit
-
Paste the PowerShell code snippet above into
.git/hooks/pre-commit.ps1
-
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! ✨
still working?