views:

83

answers:

3

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.

A: 

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 ';'

cristobalito
+6  A: 

You can use the grave accent (or 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
Joey
And don't forget to mention that some other tokens also act as line continuators e.g. `|` and `{`.
Keith Hill
@Keith: Thanks, I included it. Those were probably too obvious to mention ;-)
Joey
Nah, it's good to have these other chars documented for future reference.
Keith Hill
+2  A: 

In most C-like 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) {
        .....
    }

In the case of long pipelines, I break after the pipe character (|):

    $project.Items | 
        ? { $_.Key -eq "ProjectFile" } | 
        % { $_.Value } | 
        % { $_.EvaluatedInclude } |
        % {
            .........
        }
Jay Bazuzi