PowerShell: Pretty Format PowerShell Code 📜

By Xah Lee. Date: . Last updated: .

Install PSScriptAnalyzer

you can use PowerShell to reformat PowerShell script in a standard way.

First, install PSScriptAnalyzer from Microsoft

Install-Module -Name PSScriptAnalyzer -Force

-Force will update it if you have it installed already.

Find installed version of PSScriptAnalyzer

Get-Module -Name PSScriptAnalyzer -ListAvailable | Select-Object Version

# HHHH------------------------------

# first, call it. so it get auto imported
Invoke-Formatter -ScriptDefinition "3"

# get current imported version
(Get-Module -Name PSScriptAnalyzer).Version

Invoke-Formatter

the PSScriptAnalyzer includes a command Invoke-Formatter

Invoke-Formatter -ScriptDefinition $string
  • return a pretty formatted version of $string.
  • $string is PowerShell code.

Pretty Format PowerShell Script

put this in your PowerShell Profile

function xah-format-PowerShell-script {
    # .DESCRIPTION
    # format powershell script
    # .NOTES
    # Created: 2022-08-28
    # Version: 2024-12-22
    # .LINK
    # http://xahlee.info/powershell/powershell_format_script.html

    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $path
    )
    if ( Test-Path $path -PathType leaf ) {
        $backupName = $path + "." + (Get-Date -Format "yyyy-MM-dd_HHmmss") + "~";
        Copy-Item $path $backupName;
        $xoutput = Invoke-Formatter -ScriptDefinition ([IO.File]::ReadAllText($path));
        Set-Content $path $xoutput -NoNewline;
    }
    else {
        Write-Error "file not exist";
    }
}
xah-format-PowerShell-script filename

reformat file. also make a backup.

help xah-format-PowerShell-script

Show help.

Format PowerShell code in emacs (Emacs Integration)

Reference