PowerShell: Command to Format PowerShell Code

By Xah Lee. Date: . Last updated: .

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.

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-pwsh-script filename
reformat file. also make a backup.
help xah-format-pwsh-script
Show help.

Format PowerShell code in emacs (Emacs Integration)

PowerShell

Practical How-To

list files

list dirs

on dir

on file

Windows config

zip tar

misc


PowerShell in Depth

Programing PowerShell

Value Types

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples