PowerShell Here-String保留换行符

时间:2013-01-24 15:31:50

标签: powershell string-formatting

PowerShell代码:

$string = @'
Line 1

Line 3
'@
$string

输出:

Line 1
Line 3

但我希望它输出:

Line 1

Line 3

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:5)

在ISE中工作正常并且script也可以。 我不记得在哪里,但我读到这是控制台主机代码中的一个错误,当以交互方式输入here-string时会丢弃空行。 目前我无法测试是否修复了Powershell V.3.0控制台错误。

问题的链接:http://connect.microsoft.com/PowerShell/feedback/details/571644/a-here-string-cannot-contain-blank-line

解决方法:添加反引号`

$string = @"
Line 1
`
Line 3
"@

答案 1 :(得分:0)

另一种选择是使用: "@+[environment]::NewLine+[environment]::NewLine+@" 这可能看起来很丑,但可以根据需要运作。 上面的例子是:

$string = @"
Line 1
"@+[environment]::NewLine+[environment]::NewLine+@"
Line 3
"@

答案 2 :(得分:0)

这是另一种方式,特别是如果您不想更改此处字符串本身。这种快速解决方案对我来说非常有用,因为它可以恢复存储在Here-String / Verbatim-String 中的换行字符(CRLF)的预期行为,而无需更改Here-string < / strong>本身。您可以执行以下操作之一:

$here_str = $here_str -split ([char]13+[char]10)

OR

$here_str = $here_str -split [Environment]::NewLine

要测试,您可以进行行计数:

($here_str).Count

以下是您的示例:

$string = @'
Line 1

Line 3
'@

#Line-Count *Before*:
$string.Count         #1

$string = $string -split [Environment]::NewLine

#Line-Count *After*:
$string.Count         #3

$string

输出:

Line 1

Line 3

HTH