#中文乱码
处理中文文本时,乱码通常来自编码不一致:文件用一种编码保存,程序却用另一种编码读取;或者控制台与外部程序的编码不匹配。
#控制台输出编码
[Console]::OutputEncoding 决定 PowerShell 如何解释和显示外部程序的输出:
> [Console]::OutputEncoding
在中文 Windows 上,结果可能是 GBK(代码页 936);在 Linux 和 macOS 上通常是 UTF-8。可以显式设置为 UTF-8:
> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
如果涉及控制台输入,也可以设置 InputEncoding:
> [Console]::InputEncoding = [System.Text.Encoding]::UTF8
这些设置只影响当前会话,重启 PowerShell 后失效。需要长期生效时,可以写入配置文件(profile)。
#$OutputEncoding
$OutputEncoding 决定 PowerShell 通过管道把文本传给 外部程序 时使用的编码:
> $OutputEncoding
PowerShell 7 默认使用 UTF-8;Windows PowerShell 5.1 默认使用 ASCII,向原生命令传递中文时容易乱码。可以改为不带 BOM 的 UTF-8:
> $OutputEncoding = [System.Text.UTF8Encoding]::new($false)
#文件读写
读取和写入文件时,应显式指定编码,不要依赖平台默认值:
> Get-Content -LiteralPath ./data.txt -Encoding utf8
> Set-Content -LiteralPath ./data.txt -Value '中文内容' -Encoding utf8
- PowerShell 7 的
Set-Content默认使用 UTF-8(无 BOM)。 - Windows PowerShell 5.1 的
Set-Content默认使用 ANSI,跨平台脚本应始终写明-Encoding。 -Encoding utf8在 Windows PowerShell 5.1 中会写入 BOM,某些程序可能不识别;需要无 BOM 时使用utf8NoBOM(PowerShell 7)或 .NET API。
读取大文件并保留原始编码时,可以使用 -Raw 一次性读取:
> $text = Get-Content -LiteralPath ./data.txt -Raw -Encoding utf8
#Windows 与 Linux/macOS 的差异
| 项目 | Windows PowerShell 5.1 | PowerShell 7(跨平台) |
|---|---|---|
| 控制台默认编码 | 随系统代码页(常见 GBK) | 通常为 UTF-8 |
$OutputEncoding 默认 | ASCII | UTF-8 |
Set-Content 默认 | ANSI | UTF-8 无 BOM |
在 Windows 的 cmd.exe 中,还可以用 chcp 65001 把代码页切换为 UTF-8,但效果取决于终端和程序,不能替代脚本内的编码设置。