Pretty Format PowerShell Code
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 # .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 $formattedOutput = Invoke-Formatter -ScriptDefinition $fileText Set-Content $path $formattedOutput } else { Write-Error "file not exist" } }
xah-format-pwsh-script filename
- reformat file. also make a backup.
help xah-format-pwsh-script
- Show help.