创建文件 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 [核心,v6+] ,PowerShell的跨平台版本,现在幸运的是默认为无 BOM 的 UTF-8 在输入和输出上。
Windows PowerShell ,不同于底层的 .NET Framework[1]
, 使用以下默认值 :
>
和 >>
重定向操作符产生 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 - 如何在 PowerShell 中正确/全局地转换 UTF-8(无 BOM)文件? (到另一个文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767067/