PowerShell Line continuation

There are a number of ways to signal PowerShell line continuation in your code. probably the most common is to have a pipeline symbol at the end of the line:

Get-Process |
Sort-Object -Property CPU -Descending -Top 5

because there’s nothing after the pipe symbol PowerShell assumes that the next line of code is actually a continuation and treats the 2 lines of code as a single pipeline. This is especially good i you have a very long pipeline with incorporating numerous cmdlets.

Since the days of PowerShell v1 many people have asked to be able to the pipe symbol at the beginning of the continuation line rather than at the end of the first line. The only way you could do that was to use the backtick ` symbol to signify line continuation:

Get-Process `
| Sort-Object -Property CPU -Descending -Top 5

This is an ugly approach as the back tick is a very small character its often overlooked when reading or working with the code which can lead to bugs.

PowerShell 7 allows you to use the pipe symbol at the start of a line as a continuation character without needing the backtick:

Get-Process
| Sort-Object -Property CPU -Descending -Top 5

Over the years many people, especially those new to PowerShell, have complained that there are sometimes too many different ways in PowerShell to achieve the result you want. To my mind this change of one of those unnecessary changes that just add complexity (of choice) for no real benefit. PowerShell is an open source project and if someone wants to add something like this then the opportunity is there. I’ll be sticking to the pipe symbol at the endo of the line approach as I don’t see any advantage to changing and I find the original approach easier to understand.

Advertisements
This entry was posted in PowerShell 7. Bookmark the permalink.

4 Responses to PowerShell Line continuation

  1. Michael Trigg says:

    Agreed. I wonder how this will work interactively? That is, if I enter Get-Process on a line, and hit enter – how does the shell know that I actually want to execute Get-Process as opposed to waiting for the input of the second line?

  2. You can’t use the pipe symbol on the second line interactively. as soon as you hit enter the first line executes. Pipe symbol at the start of the continuation line has to be script/function coding use only

  3. Michael Trigg says:

    I really don’t like when there are differences between script behaviors and interactive behaviors.

  4. That’s one of the reasons I don’t like this change

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s