VSCode – PowerShell Formating

If you’ve been writing in Powershell for any period of time, you’ve at some point encountered one of the various Powershell formatting arguments. It’s always some type of semantic detail. While this post can’t fix all of those it certainly can help solve a lot of the basic arguments including how to format functions, parenthesis and more.

What do you mean different styles?

The below code are two ways in Powershell of writing the same thing. The code doesn’t run any different at all. Depending on which language you started with you’ll have different habits.

#Format 1
Function Get-Stuff 
	{
    	Write-Host "Do some stuff"
    }

#Format 2
Function Get-Stuff{
	Write-Host "Do Some stuff"
}

While this isn’t a big issue if you are a solo coder it can be extremely frustrating if you work in a team. Even worse than that is when you have that one person on the team who refuses to stop using aliases.

#Aliases 
Get-ChildItem | % {Write-host "$($_.fullName)"

#No Aliases
Get-ChildItem | ForEach-Object { Write-Host "$($_.FullName)"

Fixing It

If I had to read through 900 lines of code and fix all of that I would hate it. Fortunately VSCode has some sneaky things that can be done to help. Including the ability to perform some auto formatting. To get started we need to open up the settings in VSCode, you can do this by either navigating to “File -> Preferences -> Settings” or by using the key combination of “Ctrl + ,” together. Then type “PowerShell” in the search bar at the top.

Note: You must have Powershell extension installed

Once you’re here scroll down until you find two settings:

  • PowerShell -> Code Formatting: Auto Correct Aliases
    • powershell.codeFormatting.autoCorrectAliases
  • PowerShell -> Code Formatting: Use Correct Casing
    • powershell.codeFormatting.useCorrectCasing

Make sure these two settings are checked, there are a TON of other settings in here as well, but these two are ones are just nice examples. There are also settings that can be used to change the parenthesis. Your settings should look something like this now.

Once this is done you’ll be able to change the formatting of an entire script all at once. The first step is to highlight the entire script. Then use the following key combination to start the formatting process:

SHIFT + ALT + F

This will then format all of your code. If you don’t change any other settings it will use the DEFAULT Microsoft/VSCode approved standards.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: