PowerShell: Command to Format PowerShell Code

By Xah Lee. Date: . Last updated: .

Require PSScriptAnalyzer

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

First, download PSScriptAnalyzer from Microsoft https://docs.microsoft.com/en-us/powershell/utility-modules/psscriptanalyzer/overview

Install-Module -Name PSScriptAnalyzer -Force

that will get you a command Invoke-Formatter

Invoke-Formatter -ScriptDefinition $string

return a pretty formatted $string. The $string should be PowerShell code.

xah-format-PowerShell-script

put this in your PowerShell Profile

function xah-format-PowerShell-script {

    # .DESCRIPTION
    # format powershell script
    # version 2022-08-28
    # .LINK
    # http://xahlee.info/powershell/powershell_format_script.html

    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $path
    )

    if ( Test-Path $path -PathType leaf ) {

        $xdate = Get-Date -Format "yyyy-MM-dd_HHmmss";
        $backupName = $path + "~" + $xdate + "~";
        Copy-Item $path $backupName;

        Write-Host "backup at $backupName";

        # $fileText = Get-Content -Raw $path
        $fileText = [IO.File]::ReadAllText($path);
        $formattedOutput = Invoke-Formatter -ScriptDefinition $fileText;
        Set-Content $path $formattedOutput -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)