2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

文字化けを起こさない

Last updated at Posted at 2022-04-15

はじめに

WindowsのコマンドプロンプトやPowerShellはデフォルトのコードページがCP932であることが多いです。
このせいでWindows環境ではVS Codeのせいではありませんが、VS Codeのターミナルで文字化けが起こります。

2022/10/09 追記: Windows 11のPowershellでchcp 65001を実行しても文字化けが起こる事象を確認しています。対処法は現在調査中です。
2022/04/19 追記: より簡単なワンライナーの対処法を追加しました。

対処法1

以下のコマンドレットをVS Codeのターミナル上で実行します。

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser; ni $profile -force; echo "chcp 65001 > $null" > $profile

警告が表示されますがyを入力します。

なぜなのか

$profileに格納されているパスでスクリプトファイルを作成し、コードページをCP65001に変更するコマンドレットを書き込んでいます。
$profileのスクリプトはPowerShellの起動時に実行されます。
PowerShellの起動時にコードページをCP65001に変更することによって、UTF-8で出力されても文字化けしなくなるわけです。

しかし、PowerShellスクリプトを実行させるために実行ポリシーを変更しています。
ローカルで作成されたスクリプトは実行できるようになってしまうので、セキュリティ上のリスクが生じます。
このリスクを回避するには次の対処法を使ってください。

対処法2

上記の対処法を行っている場合、こちらを行う必要はありません。

settings.jsonに以下を追加します。

"terminal.integrated.profiles.windows": {
    "PowerShell": {
        "source": "PowerShell",
        "icon": "terminal-powershell",
        "args": [
            "-NoExit",
			"chcp",
			"65001",
            ">",
            "$null",
        ]
    },
},

ファイルの先頭から始まる大きな{}の中に入れます。

settings.jsonの開き方

Ctrl + ,のショートカットを使うか、

1.png
左下の歯車マークを押し、
2.png

設定を開きます。

3.png
右上のファイルアイコンを押します。

なぜなのか

これによってPowerShell起動時にコードページがCP65001に変更されます。
UTF-8で出力されても文字化けしなくなるわけです。
PowerShell以外に適用する場合はさらに設定を編集する必要があります。

2
1
4

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?