PowerShell Closing Brace Style

Welcome Forums General PowerShell Q&A PowerShell Closing Brace Style

This topic contains 6 replies, has 7 voices, and was last updated by

 
Keymaster
9 months, 1 week ago.

  • Author
    Posts
  • #93523

    Participant
    Points: 13
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 20
    Rank: Member

    I Always use option 3

    just looks cleaner

  • #93546

    Participant
    Points: 4
    Rank: Member

    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
    Points: 224
    Helping Hand
    Rank: Participant

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

  • #93568

    Participant
    Points: 0
    Rank: Member

    Definitely option 3 for me.

  • #93580

    Keymaster
    Points: 1,639
    Helping HandTeam Member
    Rank: Community Hero

    And definitely use VS Code.

The topic ‘PowerShell Closing Brace Style’ is closed to new replies.