Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active February 6, 2025 07:59
Show Gist options
  • Save Jaykul/a9d8e7d78c1e2fab17847dce308d281c to your computer and use it in GitHub Desktop.
Save Jaykul/a9d8e7d78c1e2fab17847dce308d281c to your computer and use it in GitHub Desktop.
When you need to reformat a bunch of PowerShell scripts
<#
.SYNOPSIS
Formats a script file using PSScriptAnalyzer
.DESCRIPTION
Formats a script file using PSScriptAnalyzer and some hard-coded rules.
There are many formatters, but this one is mine.
.EXAMPLE
Get-ChildItem -Recurse -Filter *.ps1 | Format-ScriptFile
#>
[CmdletBinding()]
param(
# The path to the script to format
[Parameter(Mandatory, ValueFromPipeline)]
[Alias("PSPath")]
$Path
)
process {
# $Tokens = $null
# $ParseErrors = $null
# $Ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$Tokens, [ref]$ParseErrors)
$FormattedText = PSScriptAnalyzer\Invoke-Formatter -ScriptDefinition (Get-Content $Path -Raw) -Settings @{
IncludeRules = @(
"PSPlaceCloseBrace"
"PSPlaceOpenBrace"
"PSUseConsistentWhitespace"
"PSUseConsistentIndentation"
"PSAlignAssignmentStatement"
"PSAvoidSemicolonsAsLineTerminators"
"PSAvoidUsingCmdletAliases"
"PSUseCorrectCasing"
)
Rules = @{
PSPlaceOpenBrace = @{
Enable = $true
OnSameLine = $true
NewLineAfter = $true
IgnoreOneLineBlock = $false
}
PSPlaceCloseBrace = @{
Enable = $true
NewLineAfter = $false
IgnoreOneLineBlock = $false
}
PSUseConsistentIndentation = @{
Enable = $true
IndentationSize = 4
Kind = "spaces"
PipelineIndentation = "IncreaseIndentationForFirstPipeline"
}
PSUseConsistentWhitespace = @{
Enable = $true
CheckOpenBrace = $true
CheckOpenParen = $true
CheckOperator = $true
CheckSeparator = $true
CheckInnerBrace = $true
CheckParameter = $true
CheckPipe = $true
CheckPipeForRedundantWhitespace = $true
}
PSAlignAssignmentStatement = @{
Enable = $false # This conflicts with PSUseConsistentWhitespace CheckOperator
CheckHashtable = $true
}
PSAvoidSemicolonsAsLineTerminators = @{
Enable = $true
}
PSAvoidUsingCmdletAliases = @{
Enable = $true
}
PSUseCorrectCasing = @{
Enable = $true
}
}
}
# $FormattedAst = [System.Management.Automation.Language.Parser]::ParseInput($FormattedText, $Path, [ref]$Tokens, [ref]$ParseErrors)
Set-Content -Path $Path -Value $FormattedText.TrimEnd() -Encoding UTF8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment