如何在 PowerShell 中捕获 UTF-8(无 BOM)文件 properly/globally? (到另一个文件)

How to cat a UTF-8 (no BOM) file properly/globally in PowerShell? (to another file)

创建文件utf8.txt。确保编码为 UTF-8(无 BOM)。将其内容设置为

cmd.exe中:

type utf8.txt > out.txt

out.txt的内容是

在 PowerShell (v4) 中:

cat .\utf8.txt > out.txt

type .\utf8.txt > out.txt

Out.txt内容为€

如何在全局范围内使 PowerShell 正常工作?

注意:此答案是关于 Windows PowerShell(最高 v5.1); PowerShell [Core, v6+],PowerShell 的跨平台 版本,现在幸运的是默认为BOM -less 输入和输出上的 UTF-8


Windows PowerShell,不同于底层 .NET Framework[1] , 使用以下默认值:

  • 输入:文件没有BOM(字节顺序标记) 被假定为 系统的 默认 编码 ,这是 legacy[=85] =] Windows code page(“ANSI”代码页:活动的、文化特定的单字节编码,通过控制面板配置)。

  • 输出>>>重定向运算符产生UTF-16 LE 默认文件(确实有 - 并且需要 - BOM)。

消耗文件和生成文件的 cmdlet 通常支持 -Encoding 参数,可让您明确指定编码。
在 Windows PowerShell v5.1 之前,明确使用底层 Out-File cmdlet 是更改编码的唯一方法。
Windows PowerShell v5.1+ 中,>>> 成为 Out-File 的有效别名,允许您更改编码行为>>> 通过 $PSDefaultParameterValues 偏好变量;例如:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'.

要使 Windows PowerShell 正确处理 UTF-8,您必须将其指定为输入和输出编码[2] ,但请注意,在 输出 上,PowerShell 总是向 UTF-8 文件添加 BOM。

应用于您的示例:

Get-Content -Encoding utf8 .\utf8.txt | Out-File -Encoding utf8 out.txt

要在 PowerShell 中创建 不带 BOM 的 UTF-8 文件,请参阅我的 this answer


[1] .NET Framework 默认使用(无 BOM)UTF-8,用于输入和输出。
Windows PowerShell 与其构建的框架之间的这种故意行为差异 不寻常 。 PowerShell [Core] v6+ 中的差异消失了:.NET [Core] 和 PowerShell [Core] 默认为无 BOM UTF-8。

但是,

[2] Get-Content 会自动识别带有 BOM 的 UTF-8 文件。

对于 PowerShell 5.1,启用此设置:

控制面板,区域,管理,更改系统区域设置,使用 Unicode UTF-8 全球语言支持

然后在 PowerShell 中输入:

$PSDefaultParameterValues['*:Encoding'] = 'Default'

或者,您可以升级到 PowerShell 6 或更高版本。

https://github.com/PowerShell/PowerShell