LoginSignup
19
22

More than 5 years have passed since last update.

日本語を含む Powershell スクリプトを UTF-8 で書く

Last updated at Posted at 2018-01-20

結論

ファイルの先頭に

$OutputEncoding='utf-8'

を付ける。

2018/03/12 追記
すいません、これ、 UTF-8 BOM にしかなりません…。
詳しくは PowerShellでBOM無しUTF8を簡単に扱う、デフォルト設定を簡単に変える方法 - しばたテックブログ

Wi-Fiのパスワードを表示するワンライナー

を以前作っていて、忘れないようにファイルに保存した。
が、これが動かなくて小一時間悩んだ。

netsh wlan show profiles | %{ $_.Split(":")[1]} | `
Where-Object{$_ -ne $null -and ( $_  -notmatch "^\s*$" ) } | `
ForEach-Object{$_.trim()} | `
ForEach-Object{ netsh wlan show profile name="$_" key=clear} | `
Where-Object{ $_ -like "*主要なコンテンツ*" -or ( $_ -like "*SSID 名*" ) } 

文字コード

結論から言うとファイルの文字コードを間違っていた。
Powershell のスクリプトを SJIS や UTF-8 BOM 以外で書くと文字化けしてしまう。
しかし、

  • Git のホスティングサービスなどに sjis を上げると面倒
  • UTF-8 BOM もなんかやだ、UTF-8 で統一させてくれ

とりあえず

こうしたら動いた。

$OutputEncoding='utf-8'
Write-Host "さようなら文字化け"
19
22
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
22