说明

遇到一个powershell Here string 中的换行导致的坑,这里来验证下不同版本中powershell here string 的行为。如果你不有心注意,很可能踩坑。

PS1 中的here string 表现

  • 不能使用空的here string ,否则你会发现在console 中敲入多次回车,这个here string 都闭合不了。
  • 如果here string 中有换行,换行会被吃掉。
    Powershell 1 here string 表现

PS2 中的here string 表现

  • 可以使用空的here string
  • 如果here string 中有换行,换行会被吃掉。

Powershell Here String 中换行在不同版本中的行为表现

PS3 中的here string 表现

同PS2,验证方法同PS2

PS4 中的here string 表现

同PS2,验证方法同PS2

PS5 中的here string 表现

  • 可以使用空的here string
  • 如果here string 中有换行,换行会被保留。
  • 换行符是\n ,而不是\r\n 也就是CRLF,这点在特定情况下影响很大(比如http Post 的数据的换行符明确要求是CRLF,少个\r ,你可能post 会出错的。)

Powershell Here String 中换行在不同版本中的行为表现

总结

  • 如果要在powershell here string 中保留换行,那么显示的方式是直接写成下面
$a=@"
`r`n
aa
"

但是你会发现,powershell 在多个版本中会给你再多加一个\n

PS C:\> $a=@"
>> `r`n
>> aa
>> "@
>>
PS C:\> $a.length
5
  • 终极解决办法,显式统一换行符为某一种
PS C:\> $a=@"
>> `r`n
>> aa
>> "@
>>
PS C:\> $a.legnth
PS C:\> $a.length
5
PS C:\> $b=$a -replace '(\r\n|\r|\n)',"`r`n"
PS C:\> $b.length
6
PS C:\> $b

aa
PS C:\>