在 VS Code 的 PowerShell 终端中出现中文乱码,通常是由于 字符编码不匹配 导致的。以下是分步解决方案:
1. 检查 PowerShell 当前编码
在 PowerShell 终端输入以下命令,查看当前输出编码:
[Console]::OutputEncoding
如果结果不是 UTF-8,则需要修改编码设置。
2. 修改 PowerShell 编码设置
方法一:临时设置(仅当前会话生效)
设置输出编码为 UTF-8
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
方法二:永久设置(推荐)
打开 PowerShell 配置文件(如果不存在会自动创建):
if (!(Test-Path -Path $PROFILE)) { New-Item -Type File -Path $PROFILE -Force } code $PROFILE
在打开的配置文件(Microsoft.PowerShell_profile.ps1)中添加以下内容:
强制设置 PowerShell 编码为 UTF-8
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
保存文件并重启 PowerShell 终端。
3. 配置 VS Code 设置
打开 VS Code 设置(Ctrl + , 或通过菜单 File > Preferences > Settings)。
搜索
terminal.integrated.defaultProfile.windows
,确保选择的是 PowerShell。
搜索
terminal.integrated.shellArgs.windows
,添加以下参数(强制终端使用 UTF-8):
"terminal.integrated.shellArgs.windows": ["-ExecutionPolicy", "Bypass", "-NoLogo", "-NoProfile", "-Command", "chcp 65001"]
(可选)在设置中添加以下配置,确保终端默认使用 UTF-8:
"terminal.integrated.defaultProfile.windows": "PowerShell", "terminal.integrated.profiles.windows": { "PowerShell": { "source": "PowerShell", "args": ["-NoExit", "-Command", "chcp 65001"] } }
4. 验证系统区域设置(Windows)
按 Win + S 搜索 区域设置,打开控制面板。
确保 Beta 版:使用 Unicode UTF-8 提供全球语言支持 已启用(需重启生效)。
5. 其他可能原因
字体问题:在 VS Code 设置中搜索 terminal.integrated.fontFamily,尝试更换为支持中文的字体(如 Consolas, 'Courier New', monospace)。
第三方工具干扰:如果使用了 ConEmu、Windows Terminal 等工具,需单独配置其编码为 UTF-8。
6. 重启 VS Code
完成所有配置后,重启 VS Code 使设置生效。
通过以上步骤,中文乱码问题通常可以解决。如果问题依旧,请检查系统语言包是否完整或尝试在 PowerShell 中运行 chcp 65001 临时切换代码页。
领取专属 10元无门槛券
私享最新 技术干货