PowerShell 輸出結果編碼問題 - 黑暗執行緒

文章推薦指數: 80 %
投票人數:10人

Do-Something.ps1 > output.txt 存檔是用ANSI/BIG5 編碼,但事實不然。

... 其編碼Export-PSSession 用UTF8(含BOM) New-Item -Type File -Value 會 ... 之前研究PowerShell中文編碼問題有個結論-Windows10內建PowerShell5.1,在中文版Windows預設用BIG5編碼,PowerShell6.0之後會預設改用UTF8。

因此我一直以為.\Do-Something.ps1>output.txt存檔是用ANSI/BIG5編碼,但事實不然。

前天介紹的Windows資料夾權限清單產生小工具有個用法是修改權限前先.\List-Acl.ps1C:\WWW|ConvertTo-Json>before.json做一次快照,修改後再做一次.\List-Acl.ps1C:\WWW|ConvertTo-Json>after.json,之後可用gitdiffbefore.jsonafter.json產生差異對照表,但實測時卻踩到雷:gitdiff判定我的json檔是二進位資料無法比對,但typeafter.json看是純文字無誤。

用NotePad++開啟after.json,謎底揭曉-用>file.txt儲存成的文字檔,編碼並非我預期的ANSI/BIG5,而是Unicode(UCS-2LEBOM/UTF-16LE):MSDocs有篇關於PowerShell編碼原則的完整說明-about_Character_Encoding-PowerShell。

整理重點如下:PowerShell5.1支援以下編碼:Ascii、BigEndianUnicode、BigEndianUTF32、Byte、Default、Oem、Unicode/String/Unknown(即UTF-16LE)、UTF32、UTF7、UTF8(含BOM)PS5.1預設使用Unicode(UTF16-LE),但有些Cmdlet有自己的編碼偏好:Out-File、>、>>用UTF-16LEAdd-Content、Set-Content、Send-MailMessage用DefaultExport-Csv建立用ASCII,附加現成檔案時則沿用其編碼Export-PSSession用UTF8(含BOM)New-Item-TypeFile-Value會建立UTF8(不含BOM)Start-Transcript建立用UTF8(含BOM),附加現成檔案時則沿用其編碼PowerShellCore(V6+)支援的編碼:ascii、bigendianunicode、oem、unicode、utf7、utf8、utf8BOM、utf8NoBOM、utf32,所有輸出預設都是用utf8NoBOM$PSDefaultParameterValues['Out-File:Encoding']='utf8'可修改特定Cmdlet的編碼、$PSDefaultParameterValues['*:Encoding']='utf8'則可修改全部Cmdlet的編碼$OutputEncoding修改對外部程式使用的編碼,但「不包含>輸出導向」實測,設定$PSDefaultParameterValues['*:Encoding']='utf8'後,.\List-Acl.ps1C:\WWW|ConvertTo-Json>after-utf8.json即會改用UTF-8BOM編碼,而我也如願用gitdiff取得修改對後對照:NotesabouthowPorwerShelldecideoutputencoding.ShareonFacebookShareonTwitterShareonGoogle+EmailCommentsBethefirsttopostacommentPostacommentCommentNameCaptcha44-16=黑暗執行緒黑暗後花園OrcsWeb:WindowsServerHosting



請為這篇文章評分?