Site icon SumTips

PowerShell Beautifier: Free Tool to Pretty Print .PS1 Script Files

Writing code can get messy, especially if you are using custom aliases or when you are cutting and pasting bits here and there. PowerShell Beautifier is a free command-line utility that formats, as you guessed it, PowerShell code, making it easier to read and validate them. It can also replace aliases and parameters with proper case and names to make your PowerShell code ‘commit-worthy.’

Download and Install PowerShell Beautifier

PowerShell Beautifier is available in PowerShell Gallery. To install it, open PowerShell as an Administrator and type in below code:

Install-Module -Name PowerShell-Beautifier

Within a few seconds it would be downloaded and installed on your PC. To verify if the installation completed correctly, type in: Get-Help Edit-DTWBeautifyScript. You should be able to see a screen as below:

How to Use PowerShell Beautifier

PowerShell Beautifier supports several parameters:

Before we start with the examples, please create a back up of your script files. Beautifier is programmed to rewrite to the final destination only if everything worked correctly; however, it’s always better to have a backup.

Beautify Single File

To use Beautifier, you just need to provide path to a script file. Be default, the source file is overwritten with two indent spaces:

Edit-DTWBeautifyScript C:\MyScripts\MyFile.ps1

We will see how to keep the source file intact and change indentation in the examples that follow.

Beautify Multiple PS Scripts in a Directory

We can run the utility on multiple scripts in a folder by filtering them based on the extension:

Get-ChildItem -Path C:\MyScripts -Include *.ps1,*.psm1 | Edit-DTWBeautifyScript

By using -Recurse parameter, this can be extended to subdirectories as well.

Use Tabs indentation

Don’t use spaces? Change indentation to Tabs with -IndentType parameter:

Edit-DTWBeautifyScript C:\MyScripts\MyFile.ps1 -IndentType Tabs

Save Formatted Code as New File

To keep the source file intact and save the clean version to a new file, specify -DestinationPath with the new file name:

Edit-DTWBeautifyScript -SourcePath C:\MyScripts\MyFile.ps1 -DestinationPath C:\MyScripts\MyCleanFile.ps1

Change New Line Style

By default, the beautifier uses the host OS’s style for newlines. To override this, use -NewLine:

Edit-DTWBeautifyScript C:\MyScripts\MyFile.ps1 -NewLine LF

Overall, Beautifier is a useful tool to run your code through before sharing or publishing online. It would make code easier to read and also standardize the format. Hit this link to get the latest version from PowerShell Gallery.