219 字
1 分钟
PowerShell 中文乱码修复方案
2026-07-20

PowerShell 中文乱码是 Windows 老问题,AI 工具(OpenCode、Codex CLI 等)中尤其严重——常规的 $PROFILE 修复方案对它们无效,因为这些工具启动 PowerShell 时带 -NoProfile 参数。

问题根源是两个编码变量:$OutputEncoding 默认 US-ASCII(管道中文变问号),[Console]::OutputEncoding 默认 GB2312。AI 工具按 UTF-8 解码 stdout,PowerShell 却按 GB2312 编码输出,必乱。

方案一:自动#

发给 agent 执行即可:

Terminal window
# 注册表:绕过 -NoProfile,让 PowerShell 默认输出 UTF-8
$key = "HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe"
New-ItemProperty -Path $key -Name "CodePage" -Value 65001 -PropertyType DWord -Force | Out-Null
# Profile:交互式终端的双重保障
$profileDir = Split-Path $PROFILE -Parent
if (-not (Test-Path $profileDir)) { New-Item -Path $profileDir -ItemType Directory -Force | Out-Null }
@"
`$OutputEncoding = [System.Text.UTF8Encoding]::new(`$false)
[System.Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(`$false)
[System.Console]::InputEncoding = [System.Text.UTF8Encoding]::new(`$false)
"@ | Out-File -FilePath $PROFILE -Encoding utf8 -Append
# Python 环境变量
[Environment]::SetEnvironmentVariable("PYTHONIOENCODING", "utf-8", "User")
Write-Host "配置完成,重启终端生效" -ForegroundColor Green

方案二:手动#

Terminal window
# 一行搞定注册表
New-ItemProperty -Path "HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe" -Name "CodePage" -Value 65001 -PropertyType DWord -Force

只影响当前用户的 PowerShell,不碰系统全局代码页。注册表是进程级默认值,-NoProfile 下也生效。

可选步骤——Profile 添加:

Terminal window
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)
[System.Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
[System.Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)

Python 环境变量:设置 → 系统 → 高级系统设置 → 环境变量 → 新建,变量名 PYTHONIOENCODING,值 utf-8

验证#

Terminal window
echo "你好世界"

影响#

findstr 管道匹配中文会失效,改用 Select-String。其余场景全部正常。回滚只需删除注册表中 CodePage 值。

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

PowerShell 中文乱码修复方案
https://blog.nth2miss.cn/posts/powershell-utf8-encoding-fix/
作者
Nth2Miss
发布于
2026-07-20
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录