溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Powershell Here String 中換行在不同版本中的行為表現(xiàn)

發(fā)布時間:2020-06-22 01:33:02 來源:網(wǎng)絡(luò) 閱讀:3626 作者:yoke88 欄目:開發(fā)技術(shù)

說明

遇到一個powershell Here string 中的換行導(dǎo)致的坑,這里來驗證下不同版本中powershell here string 的行為。如果你不有心注意,很可能踩坑。

PS1 中的here string 表現(xiàn)
  • 不能使用空的here string ,否則你會發(fā)現(xiàn)在console 中敲入多次回車,這個here string 都閉合不了。
  • 如果here string 中有換行,換行會被吃掉。
    Powershell Here String 中換行在不同版本中的行為表現(xiàn)
PS2 中的here string 表現(xiàn)
  • 可以使用空的here string
  • 如果here string 中有換行,換行會被吃掉。

Powershell Here String 中換行在不同版本中的行為表現(xiàn)

PS3 中的here string 表現(xiàn)

同PS2,驗證方法同PS2

PS4 中的here string 表現(xiàn)

同PS2,驗證方法同PS2

PS5 中的here string 表現(xiàn)
  • 可以使用空的here string
  • 如果here string 中有換行,換行會被保留。
  • 換行符是\n ,而不是\r\n 也就是CRLF,這點在特定情況下影響很大(比如http Post 的數(shù)據(jù)的換行符明確要求是CRLF,少個\r ,你可能post 會出錯的。)

Powershell Here String 中換行在不同版本中的行為表現(xiàn)

總結(jié)

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

但是你會發(fā)現(xiàn),powershell 在多個版本中會給你再多加一個\n

PS C:\> $a=@"
>> `r`n
>> aa
>> "@
>>
PS C:\> $a.length
5
  • 終極解決辦法,顯式統(tǒng)一換行符為某一種
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:\>
向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI