Is it possible to split a PowerShell command line over multiple lines?
In Visual Basic I can use the underscore (_
) to continue the command in the next line.
Is it possible to split a PowerShell command line over multiple lines?
In Visual Basic I can use the underscore (_
) to continue the command in the next line.
You can use a space followed by the grave accent (backtick):
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:
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:Similar to the
|
a comma will also work in some contexts: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:
will not work.
Finally, strings (in all varieties) may also extend beyond a single line:
They include the line breaks within the string, then.
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:
if the script block is very long, you might want to write:
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: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:
Simlarly, in the case of long pipelines, I break after the pipe character (
|
):To expand on cristobalito's answer:
For example:
Sign a PowerShell script on the command-line. No line breaks.
;
to separate command\\
on any backslashes\
."'
for passing safe address to switch command like "'PATH'".This ps1 command install locale pfx certificate.
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.
I assume you're talking about on the command-line - if it's in a script, then a new-line acts as a command delimiter.
On the command line, use a semi-colon ';'