PowerShell中的Here-String保留换行符

6

PowerShell代码:

$string = @'
Line 1

Line 3
'@
$string

输出:

Line 1
Line 3

但我希望它能输出:
Line 1

Line 3

我该如何实现这个目标?

它在PS3.0和PS2.0中都保留了换行符。 - Frode F.
3个回答

6

2
谢谢。我确认这个Bug在PS V3控制台中仍然存在。 - Elijah W. Gagne
1
可以确认在PS V5中仍然存在。 - Douglas Plumley
仍然存在于PS v5.1.14409.1018(Windows 8.1)中,但自PS v5.1.18362.752(Windows 10 1909)以来已得到修正。 - Petru Zaharia

0
另一个选项是使用: "@+[environment]::NewLine+[environment]::NewLine+@" 虽然看起来不太美观,但可以按照需要工作。 上面的示例将变为:
$string = @"
Line 1
"@+[environment]::NewLine+[environment]::NewLine+@"
Line 3
"@

0

还有另一种方法,特别是如果您不想更改字符串本身。这个快速的解决方案对我非常有效,因为它恢复了 Here-String / Verbatim-String 中存储的预期 New-Line 字符(CRLF)的行为而不必更改 Here-String 本身。您可以做的是:

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

或者

$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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接