PowerShell 重定向写出中文乱码

命令行难度 2/5约 2 分钟

问题现象

用 PowerShell 生成一个带中文的文本文件,自己看没问题,但交给 Node 或 Python 读就变成乱码:

powershell
"配置项:中文内容" | Out-File config.txt

用 Node 读取:

js
import fs from 'node:fs';
console.log(fs.readFileSync('config.txt', 'utf8'));
// 输出:閰嶇疆椤癸細涓枃鍐呭

同时,反过来也出问题:Node 写出的 UTF-8 文件用 Get-Content 读,中文同样是乱码。

排查过程

  1. 先看文件到底用什么编码写的:
powershell
Format-Hex config.txt | Select-Object -First 3

前两个字节是 EF BB 说明带 UTF-8 BOM,是 FF FE 说明是 UTF-16LE, 是 C5 E4 之类的就是 GBK(也就是当前系统代码页)。

  1. 再看 PowerShell 自己认为的默认编码:
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 读取,于是中文就散了。

解决办法

写文件时显式指定编码,不要依赖默认值:

powershell
# 推荐:明确写出无 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

读文件时顺手指定编码:

powershell
Get-Content config.txt -Encoding utf8

顺带把控制台输出编码也调成 UTF-8,避免调用外部程序时串码:

powershell
[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 生成更省事。

相关问题

PowerShell 里 && 不能用来连接命令

命令行难度 1/5约 1 分钟

从文档里复制来的 npm run build && npm run serve 在 Windows 上直接报错,因为 && 是 PowerShell 7 才支持的语法。

端口被占用导致开发服务器打开的是旧实例

环境配置难度 2/5约 2 分钟

启动开发服务器报 EADDRINUSE,而「以为没生效」的页面其实是上一次没关掉的进程在响应。