Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Here-String that keeps newlines

The PowerShell code:

$string = @'
Line 1

Line 3
'@
$string

Outputs:

Line 1
Line 3

But I want it to output:

Line 1

Line 3

How can I achieve that?

like image 619
Elijah W. Gagne Avatar asked Jan 24 '13 15:01

Elijah W. Gagne


People also ask

What is a here-string in PowerShell?

PowerShell Here-String is the method of inserting the multiple lines of the strings or the commands inside the enclosure, also known as the string array, and the best way of representing the data with the free text and string block is represented by the @” “@ with either single-quote or the Double-quote inside which ...

How to give a line break in PowerShell?

Use the `n Code Method The most common technique for forcing a line break is to insert `n just before the character where you want the break to occur. Note that the ` character is the backtick, not an apostrophe.

How do you continue a line in PowerShell?

Backtick (`) character is the PowerShell line continuation character. It ensures the PowerShell script continues to a new line. To use line continuation character in PowerShell, type space at the end of code, use backtick ` and press enters to continue to new line.

How do I replace a string in PowerShell?

You can call the PowerShell replace method on any string to replace any literal string with another. If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string.


1 Answers

In ISE works fine and in script works too. I don't remember where, but I read that is a bug in the console host code and empty lines are discarded when entered interactively for here-string. At the moment I can't test if in Powershell V.3.0 console bug is fixed.

Link to the issue: http://connect.microsoft.com/PowerShell/feedback/details/571644/a-here-string-cannot-contain-blank-line

Workaround: add a backticks `

$string = @"
Line 1
`
Line 3
"@
like image 145
CB. Avatar answered Oct 18 '22 08:10

CB.