- 此教程是为了解决在使用 AI Coding 时候, 读取项目文件提示代码乱码问题.
- 以下内容只修改 pwsh 默认编码问题, Vscode, Pycharm 等 IDE.
- 需要手动修改默认 powershell 为 7.x 版本, 否则默认还是 5.x 版本.
安装 Powershell 7
- 查看当前 Powershell 版本
$PSVersionTable
输出如下
PSVersion 7.5.4
如果使用的是 Powershell 5.x 建议升级到 Powershell 7.x, 对 UTF-8 支持会更好.
- 搜索最新版本的 PowerShell
winget search --id Microsoft.PowerShell
输出如下
Name Id Version Source
---------------------------------------------------------------
PowerShell Microsoft.PowerShell 7.5.4.0 winget
PowerShell Preview Microsoft.PowerShell.Preview 7.6.0.6 winget
- 使用
--id参数安装 PowerShell 或 PowerShell 预览版
winget install --id Microsoft.PowerShell --source winget
winget install --id Microsoft.PowerShell.Preview --source winget
- 打开 pwsh 查看默认编码, 注意
powershell指令默认打开为 5.x 版本,pwsh打开为 7.x 版本
chcp
如果输出不是为 65001 就不是 UTF-8 编码
Active code page: 65001
永久生效
- 打开 pwsh 终端运行
$PROFILE
输出如下, 如果不是以下路径就说明打开的不是 Powershell 7
C:\Users\你的用户名\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
- 然后编辑文件, 没有就创建添加以下内容
# ==============================
# Force UTF-8 everywhere
# ==============================
$utf8 = [System.Text.UTF8Encoding]::new($false) # UTF-8 without BOM
[Console]::InputEncoding = $utf8
[Console]::OutputEncoding = $utf8
# PowerShell cmdlets default encoding
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
# Try to align Windows console code page
try {
chcp 65001 | Out-Null
} catch {}
- 然后重新打开 pwsh 检查默认编码
chcp
输出如下
Active code page: 65001