53

I've done a fair bit of programming in C#, but then I've also written a lot of T-SQL scripts. C# requires semicolons, and T-SQL and PowerShell they're optional. What do you do for PowerShell? Why? My gut feel is to include semicolons but I don't know why.

Mark Allison
  • 2,098
  • 7
  • 26
  • 45
  • Are you talking about semicolons to end the line? this question is offtopic. – Hex Oct 29 '12 at 12:07
  • 2
    @Hex: Why would it be off topic? PowerShell is used to administer you machine, so why not... – Bart De Vos Oct 29 '12 at 13:14
  • @Hex Yes at the end of a line. Why is it off-topic? – Mark Allison Oct 29 '12 at 13:52
  • Mark Allison, sorry it was my mistake because I misunderstood your question. In linux powershell you do not need to add semicolons same as you dont need to add semicolons in MS DOS. – Hex Oct 29 '12 at 14:54
  • 1
    It's because there are squiggly brackets. Those and semicolons are like chocolate and peanut butter. They're inseparable. I blame Kernighan and Ritchie.. – Brain2000 Dec 02 '18 at 02:57
  • 1
    Best PowerShell Practice and Style: [**Avoid Using Semicolons (`;`) as Line Terminators**](https://poshcode.gitbook.io/powershell-practice-and-style/style-guide/code-layout-and-formatting#avoid-using-semicolons-as-line-terminators) PowerShell will not complain about extra semicolons, but they are unnecessary, and can get in the way when code is being edited or copy-pasted. They also result in extra do-nothing edits in source control when someone finally decides to delete them. They are also unnecessary when declaring hashtables if you are already putting each element on its own line. – iRon Sep 07 '22 at 09:58

2 Answers2

69

Powershell primarily uses new lines as statement seperators, but semicolons may be used for multiple statements on a single line.

Zoredache
  • 128,755
  • 40
  • 271
  • 413
  • 1
    Note that there is a practical difference between running each statement as its own command versus running multiple statements within a single command, as can be seen in [this question](https://superuser.com/questions/1383533/if-powershell-command-separator-is-semicolon-why-does-date-dir-make-dir). My personal decision is to not use semi-colons so that my test results in an interactive session align with what my script will receive when it runs the commands. – Anthony DiSanti Sep 03 '21 at 18:24
  • 1
    The semicolon is unnecessary so it's better to leave it out. – jim birch May 18 '22 at 02:57
25

The key, no matter whether you choose to use semicolons or not, is to be consistent. If you are used to using them in C#, then continue to use them in PowerShell. If you don't want to use them, then don't use them. Pick a standard and stick with it for you and the people that will read and use your code. It will get ugly if you decide halfway through a project to start using them.

Andy Schneider
  • 1,533
  • 5
  • 19
  • 28