Powershell Here String 中換行在不同版本中的行為表現
阿新 • • 發佈:2018-02-07
ps1 換行符 方式 col 數據 pla 裏來 多個 統一 說明
遇到一個powershell Here string 中的換行導致的坑,這裏來驗證下不同版本中powershell here string 的行為。如果你不有心註意,很可能踩坑。
PS1 中的here string 表現
- 不能使用空的here string ,否則你會發現在console 中敲入多次回車,這個here string 都閉合不了。
- 如果here string 中有換行,換行會被吃掉。
PS2 中的here string 表現
- 可以使用空的here string
- 如果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 中保留換行,那麽顯示的方式是直接寫成下面
$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:\>
Powershell Here String 中換行在不同版本中的行為表現