Indentation and Formatting Style for PowerShell Code

My preferred indentation style when writing PowerShell code is Stroustrup style because I don't like my code to cuddle (there's no cuddled else in Stroustrup style). I occasionally hear from others that they don't like this style because it doesn't work from the PowerShell console.

1if ($plasterParams.Git) {
2    $ModulePath = "$($plasterParams.DestinationPath)\$($plasterParams.GitRepoName)\$($plasterParams.Name)"
3}
4else {
5    $ModulePath = "$($plasterParams.DestinationPath)\$($plasterParams.Name)"
6}

no-asterisks2a.png

While it doesn't work by default, there's a trick to making that style work from the PowerShell console. Simply press Shift+Enter instead of just Enter at the end of the line before the else.

no-asterisks3a-1.png

I also prefer to write my code with the curly brace on the same line.

1function Get-Something {
2    #Does Something
3}

Why? Because I like consistency. Writing code with the curly brace on the next line, like in the following example, doesn't work every time. You end up having to modify how things are done on a case by case basis. For example, you can't place the curly brace for Where-Object on the next line. I even tried the Shift+Enter trick with no luck.

1function Get-Something
2{
3    #Does Something
4{

According to a discussion on the Unofficial PowerShell Best Practices and Style Guide, using both of these styles is technically a combination of Stroustrup style and the One True Brace Style variant (OTBS) variant of K&R. There was also another interesting discussion about Where to put braces in the same style guide a while back.

What's your preferred code writing style for PowerShell and why? Whatever style you choose, stick with it and be consistent. Formatting your code is a form of art in itself. If you're contributing to someone else's code such as an open-source project on GitHub, be sure to follow their formatting style as refactoring all of their code to your style won't be well received to say the least.


Update 9/6/18

Joel Bennett mention on Twitter that Shift + Enter requires PSReadline. I did some testing and indeed it does, but what I also found out is that Else can be on a separate line and it works by default without having to use Shift + Enter as long as the PSReadline module isn't loaded.

µ