OpenCode 配置 UTF-8 Shell(Windows)
OpenCode 在 Windows 上默认调用 PowerShell,并且以 -NoProfile 启动,不会加载用户的 PowerShell 配置文件。这导致终端编码无法自动设置为 UTF-8,中文输入 / 输出会出现乱码。
下面记录一种简单有效的解决方式:通过自定义 pwsh.cmd 启动脚本强制切换 UTF-8,并在 OpenCode 配置中把 shell 指向该脚本。
问题现象
启动 OpenCode 后,PowerShell 输出中文出现乱码:
����λ�� ��:1 �ַ�: 68
+ System.Management.Automation.PSVersionHashTable.PSVersion.ToString()解决步骤
1. 创建 UTF-8 启动脚本
在 OpenCode 配置目录创建 pwsh.cmd(路径可自定义):
batch
@echo off
chcp 65001 >nul
pwsh.exe %*chcp 65001:将控制台代码页切换为 UTF-8pwsh.exe %*:调用 PowerShell 7 并透传所有参数
2. 修改 OpenCode 配置
编辑 C:\Users\12500\.config\opencode\opencode.json,添加 shell 字段:
json
{
"$schema": "https://opencode.ai/config.json",
"shell": "C:\\Users\\12500\\.config\\opencode\\pwsh.cmd",
"provider": {
...
}
}重启 OpenCode 后生效。
3. (可选)双重保险:PowerShell 配置文件
如果仍有乱码,可在 PowerShell 配置文件 $PROFILE 中补一段编码设置,确保输入 / 输出均为 UTF-8:
powershell
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null验证
重启后输出测试:
powershell
Write-Output "中文测试:你好世界,开工了"写入文件再读取,字节验证:
powershell
"E4 B8 AD E6 96 87" | % { [Convert]::FromHexString($_) }
# 中 -> 0xE4 0xB8 0xAD,文 -> 0xE6 0x96 0x87如果看到标准 UTF-8 字节序(E4 B8 AD 对应“中”),说明配置成功。
小结
- OpenCode 默认
-NoProfile启动 → 不读$PROFILE→ 编码丢失 - 通过
pwsh.cmd+chcp 65001强制 UTF-8 - 在
opencode.json中把shell指向脚本即可全局生效
