PowerShell 重定向写出中文乱码
问题现象
用 PowerShell 生成一个带中文的文本文件,自己看没问题,但交给 Node 或 Python 读就变成乱码:
"配置项:中文内容" | Out-File config.txt用 Node 读取:
import fs from 'node:fs';
console.log(fs.readFileSync('config.txt', 'utf8'));
// 输出:閰嶇疆椤癸細涓枃鍐呭同时,反过来也出问题:Node 写出的 UTF-8 文件用 Get-Content 读,中文同样是乱码。
排查过程
- 先看文件到底用什么编码写的:
Format-Hex config.txt | Select-Object -First 3前两个字节是 EF BB 说明带 UTF-8 BOM,是 FF FE 说明是 UTF-16LE,
是 C5 E4 之类的就是 GBK(也就是当前系统代码页)。
- 再看 PowerShell 自己认为的默认编码:
[Console]::OutputEncoding
$OutputEncoding在中文 Windows 上,[Console]::OutputEncoding 通常是 GBK(代码页 936)。
根因
Windows PowerShell 5.1 的默认编码跟随系统区域设置,在中文环境下是 GBK,
而且 Out-File 在 5.1 里写 utf8 时会带上 BOM。其它现代工具(Node、Python、Git)
默认按无 BOM 的 UTF-8 读取,于是中文就散了。
解决办法
写文件时显式指定编码,不要依赖默认值:
# 推荐:明确写出无 BOM 的 UTF-8(5.1 和 7 都适用)
[System.IO.File]::WriteAllText("$PWD\config.txt", "配置项:中文内容", [System.Text.UTF8Encoding]::new($false))
# 简单场景:Out-File 指定编码
"配置项:中文内容" | Out-File -FilePath config.txt -Encoding utf8读文件时顺手指定编码:
Get-Content config.txt -Encoding utf8顺带把控制台输出编码也调成 UTF-8,避免调用外部程序时串码:
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)复盘
- 跨工具传中文,永远显式指定 UTF-8,不要相信「默认」。
-Encoding utf8在 5.1 和 7 里行为不同:7 默认无 BOM,5.1 默认带 BOM。
需要稳定结果时用UTF8Encoding($false)这种写法。- 内容多或结构复杂时,别用 PowerShell 拼文件,交给 Node 或 Python 生成更省事。