Author Posts

February 13, 2018 at 9:44 am

Which of these two code samples has the correct formatting?

if ($string -eq 'Hello') {
         Write-Output "Hello World!" 
         }
if ($string -eq 'Hello') {
         Write-Output "Hello World!" 
}

PowerShell ISE places the closing brace like the first example, after hitting the return key.

I use the first example and the ISE, and a colleague is telling me this is incorrect.

February 13, 2018 at 10:41 am

There's 3 basic choices – I've added the third

$string = 'Hello'

if ($string -eq 'Hello') {
         Write-Output "Hello World!" 
         }

if ($string -eq 'Hello') {
   Write-Output "Hello World1!" 
}

if ($string -eq 'Hello') 
{
   Write-Output "Hello World2!" 
}

I use option 2

A lot of people will tell you that you SHOULD use option 3

THERE IS NO WRONG WAY OR RIGHT WAY

Write in the style that looks right for YOU. Style is a subjective thing that many people think should be dictated. There a best practices in coding – like use full cmdlet and parameter names – that should be followed but as far as I'm concerned as long as the code is readable and consistent it works.

Back in the Middle Ages European philosophers would argue about how many angels could dance on the head of a pin. Brace positioning is a similar argument

February 13, 2018 at 11:42 am

I Always use option 3

just looks cleaner

February 13, 2018 at 2:47 pm

I have always used Option 2. Option 3 I could get used to but not really a fan of Option 1. None are incorrect, just whatever you are more comfortable with is good.

February 13, 2018 at 3:24 pm

That's a lame feature in ISE then. Vscode would bring it back under the If.

February 13, 2018 at 4:40 pm

Definitely option 3 for me.

February 13, 2018 at 5:35 pm

And definitely use VS Code.