eXXL
eXXL

Reputation: 7228

How to enter a multi-line command

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.

Upvotes: 701

Views: 689159

Answers (16)

sysarchitek
sysarchitek

Reputation: 33

For string. You may use Here-String syntax for multiline string assignment like

echo @"
here is the first string
location is $global:loc
"@

Ref: https://devblogs.microsoft.com/scripting/powertip-use-here-strings-with-powershell/

Upvotes: 0

Asad Shakeel
Asad Shakeel

Reputation: 2325

In Windows PowerShell as well as PowerShell 7+ (Core), you can use backticks ` to split your command across multiple lines. This makes the command more readable and easier to understand.

Note: At the time of writing, multiline commands do not work with the embedded PowerShell in Visual Studio.

Here is an example:

kiota generate `
--language csharp `
--class-name ApiClient `
--namespace-name MyNamespace `
--openapi ./Path/To/swagger.json `
--output ./OutputDirectory `
--exclude-backward-compatible `
--include-path /api/endpoint#GET

Upvotes: 21

Neffets
Neffets

Reputation: 1503

There must not be any character between the backtick and the line break. Even whitespace will cause the command to not work.

Upvotes: 132

Johannes
Johannes

Reputation: 2992

In windows terminal (powershell profile) I can simply click Shift-Enter works fine for me.

PS C:\xxx2021> Get-ChildItem -Include *remote* -Recurse |
>> Sort-Object -Property LastWriteTime -Descending  |
>> Select-Object LastWriteTime, Name -First 25

LastWriteTime        Name
-------------        ----
12/5/2021 5:04:02 PM remote-control-car-BatteryPack-Number-2021-12-03.pdf

PS C:\xxx2021>enter code here

Upvotes: 0

ninMonkey
ninMonkey

Reputation: 7511

This is an old post, so here's the modern method.

If you're not using legacy powershell, the cleanest way to continue lines is the pipe at the start of the line.

enter image description here

Note: The command doesn't break with some lines commented out. This is great on the command line.

> Get-ChildItem -path 'c:\' -Depth 1                 
    | Sort-Object LastWriteTime                       
    # | Sort-Object Length -Descending                   
    | Select-Object -First 3 -Skip 3                   
    | Foreach-Object {                                 
      $_.Name, $_.Length | Join-String -Separator ' = '                                                       
    }                                                  

output:

explorer.exe = 4826160                                 
procexp.old.exe = 2925760                              
RtlExUpd.dll = 2839488                                 

Windows Powershell ( Version < 6 )

Unfortunately windows powershell does not support it. A bunch of alternatives are linked above. You can remove the backtick completely: 2017/07/bye-bye-backtick-natural-line

Upvotes: 4

JanRK
JanRK

Reputation: 167

I started by doing

if ($true) {
"you can write multiple lines here, and the command doesn't run untill you close the bracket"

"like this"
}

Recently found out I could just

&{
get-date
"more stuff"
}

Upvotes: 4

Jian Huang
Jian Huang

Reputation: 1185

Just add a corner case here. It might save you 5 minutes. If you use a chain of actions, you need to put "." at the end of line, leave a space followed by the "`" (backtick). I found this out the hard way.

$yourString = "HELLO world! POWERSHELL!". `
                  Replace("HELLO", "Hello"). `
                  Replace("POWERSHELL", "Powershell")

Upvotes: 14

Mykhaylo Adamovych
Mykhaylo Adamovych

Reputation: 20986

$scriptBlock = [Scriptblock]::Create(@'
  echo 'before'
  ipconfig /all
  echo 'after'
'@)

Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlock

source
don't use backquote

Upvotes: 2

js2010
js2010

Reputation: 27606

There's sooo many ways to continue a line in powershell, with pipes, brackets, parentheses, operators, dots, even with a comma. Here's a blog about it: https://get-powershellblog.blogspot.com/2017/07/bye-bye-backtick-natural-line.html

You can continue right after statements like foreach and if as well.

Upvotes: 2

Moslem Shahsavan
Moslem Shahsavan

Reputation: 1337

  1. Use a semi-colon ; to separate command
  2. Replace double backslash \\ on any backslashes \.
  3. Use "' for passing safe address to switch command like "'PATH'".

This ps1 command install locale pfx certificate.

powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"

Upvotes: 2

Joey
Joey

Reputation: 354834

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:

'Foo
bar'

They include the line breaks within the string, then.

Upvotes: 967

Bad
Bad

Reputation: 5339

In PowerShell and PowerShell ISE, it is also possible to use Shift + Enter at the end of each line for multiline editing (instead of standard backtick `).

Upvotes: 24

Alex
Alex

Reputation: 389

To expand on cristobalito's answer:

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

For example:

Sign a PowerShell script on the command-line. No line breaks.

powershell -Command "&{$cert=Get-ChildItem –Path cert:\CurrentUser\my -codeSigningCert ; Set-AuthenticodeSignature -filepath Z:\test.ps1 -Cert $cert}

Upvotes: 38

Steve Fellwock
Steve Fellwock

Reputation: 69

If you are trying to separate strings into multiple lines, you can use the "+". For example:

$header =    "Make," +

             "ComputerName," +

             "Model," +

             "Windows Version"

Will look just like:

$header = "Make,ComputerName,Model,Windows Version"

Upvotes: 6

Jay Bazuzi
Jay Bazuzi

Reputation: 46546

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 } |
        % {
            .........
        }

Upvotes: 47

cristobalito
cristobalito

Reputation: 4282

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

Upvotes: 2

Related Questions