How to enter a multi-line command
You can use a space followed by the grave accent (backtick):
Get-ChildItem -Recurse ` -Filter *.jpg ` | Select LastWriteTime
However, this is only ever necessary in such cases as shown above. Usually you get automatic line continuation when a command cannot syntactically be complete at that point. This includes starting a new pipeline element:
Get-ChildItem | Select Name,Length
will work without problems since after the |
the command cannot be complete since it's missing another pipeline element. Also opening curly braces or any other kind of parentheses will allow line continuation directly:
$x=1..5$x[ 0,3] | % { "Number: $_"}
Similar to the |
a comma will also work in some contexts:
1,2
Keep in mind, though, similar to JavaScript's Automatic Semicolon Insertion, there are some things that are similarly broken because the line break occurs at a point where it is preceded by a valid statement:
return 5
will not work.
Finally, strings (in all varieties) may also extend beyond a single line:
'Foobar'
They include the line breaks within the string, then.
I just found out that there must not be any character between the back tick and the line break. Even whitespace will cause the command to not work.
In most C-like languages I am deliberate about placing my braces where I think they make the code easiest to read.
PowerShell's parser recognizes when a statement clearly isn't complete, and looks to the next line. For example, imagine a cmdlet that takes an optional script block parameter:
Get-Foo { ............ }
if the script block is very long, you might want to write:
Get-Foo { ............... ............... ............... }
But this won't work: the parser will see two statements. The first is Get-Foo
and the second is a script block. Instead, I write:
Get-Foo { ............... ............... ............... }
I could use the line-continuation character (`) but that makes for hard-to-read code, and invites bugs.
Because this case requires the open brace to be on the previous line, I follow that pattern everywhere:
if (condition) { ..... }
Note that
if
statements require a script block in the language grammar, so the parser will look on the next line for the script block, but for consistency, I keep the open brace on the same line.
Simlarly, in the case of long pipelines, I break after the pipe character (|
):
$project.Items | ? { $_.Key -eq "ProjectFile" } | % { $_.Value } | % { $_.EvaluatedInclude } | % { ......... }