PowerShell Closing Brace Style

This topic contains 6 replies, has 7 voices, and was last updated by  Don Jones 3 months ago.

  • Author
    Posts
  • #93523

    GlacialSpike
    Participant

    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.

  • #93526

    Richard Siddaway
    Moderator

    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

  • #93528

    Mark Prior
    Participant

    I Always use option 3

    just looks cleaner

  • #93546

    Brett
    Participant

    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.

  • #93550

    js
    Participant

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

  • #93568

    Harley Thorne
    Participant

    Definitely option 3 for me.

  • #93580

    Don Jones
    Keymaster

    And definitely use VS Code.

You must be logged in to reply to this topic.