Windows PowerShellとクロスプラットフォームのPowerShellでファイル出力した際にエンコーディングがどうなるかまとめ。
本記事では実際にファイルを出力してどうなっているか確認してみます。
ドキュメント
今回確認に利用するPowerShellバージョン
- Windows PowerShell 5.1.19041.2364
- PowerShell 7.3.2
実際にファイル出力して確認してみる
ここではWindows PowerShellとPowerShellで実際にファイルを出力して、どうなっているか確認してみます。
Windows PowerShellとPowerShellそれぞれで起動してコマンドを実施してもいいのですが、それぞれ起動するのも面倒なので下記のようにコマンドでWindows PowerShell(powershell.exe)とPowerShell(pwsh.exe)をそれぞれを呼び出して引数で実行するコマンドを渡して実行します。
# Windows PowerShell(powershell.exeで実行)
powershell -Command "'helloworld'>C:\temp\encode\powershell-redirect.txt"
powershell -Command "'helloworld' | Out-File C:\temp\encode\powershell-out-file.txt"
powershell -Command "'helloworld' | Out-File -Encoding utf8 c:\temp\encode\powershell-out-file-utf8.txt"
# PowerShell(pwsh.exeで実行)
pwsh -Command "'helloworld'>C:\temp\encode\pwsh-redirect.txt"
pwsh -Command "'helloworld' | Out-File C:\temp\encode\pwsh-out-file.txt"
pwsh -Command "'helloworld' | Out-File -Encoding utf8 c:\temp\encode\pwsh-out-file-utf8.txt"
# pwshではエンコーディングにutf8BOMとutf8NoBOMもあるのでこれも一応確認
pwsh -Command "'helloworld' | Out-File -Encoding utf8BOM c:\temp\encode\pwsh-out-file-utf8BOM.txt"
pwsh -Command "'helloworld' | Out-File -Encoding utf8NoBOM c:\temp\encode\pwsh-out-file-utf8NoBOM.txt"
確認結果
Windows PowerShellでリダイレクト
Windows PowerShellでOut-File エンコード指定なし
Windows PowerShellでOut-File エンコード utf8指定
PowerShellでリダイレクト
PowerShellでOut-File エンコード指定なし
PowerShellでOut-File エンコード utf8指定
PowerShellでOut-File エンコード utf8BOM指定
PowerShellでOut-File エンコード utf8NoBOM指定
まとめ
項目 | 結果 |
---|---|
Windows PowerShellでリダイレクト出力 | UTF-16 LE |
Windows PowerShellでOut-File エンコード指定なし | UTF-16 LE |
Windows PowerShellでOut-File エンコード utf8指定 | UTF-8 (BOM付き) |
PowerShellでリダイレクト出力 | UTF-8 (BOMなし) |
PowerShellでOut-File エンコード指定なし | UTF-8 (BOMなし) |
PowerShellでOut-File エンコード utf8指定 | UTF-8 (BOMなし) |
PowerShellでOut-File エンコード utf8BOM | UTF-8 (BOM付き) |
PowerShellでOut-File エンコード utf8NoBOM | UTF-8 (BOMなし) |
PowerShell
上記ドキュメントには
PowerShell (v6 以降) では、すべてのテキスト出力に対して が既定で に utf8NoBOM 設定されます。
と記載がありますが、下記ページにPowerShell Coreになって変化していった変遷がわかりやすく記載があります。
参考 PowerShell 6.0からファイル出力に関わるエンコーディングが変わります
総評
色々と互換性の事を考えるとUTF8のBOMなしで出力するのが良さそうです。
Windows PowerShellではUTF8をBOMなしで出力しようとすると、ひと手間かける必要がありますが、クロスプラットフォームなPowerShellなら何も考えずにUTF8になってくれるのは便利だと感じます。