用 Out-File -Encoding utf8 输出 UTF-8 文件

PowerShell 重定向输出的文件在别的工具里乱码?就是忘了这个编码参数。

Windows文件编码PowerShell低风险
用管道接 Out-File -Encoding utf8 显式指定编码,不要依赖重定向符的默认值。

01命令

命令
$ Get-ChildItem C:\Reports | Out-File -FilePath 'C:\Temp\list.txt' -Encoding utf8

02作用说明

在 Windows PowerShell 5.1 中,'>' 和 Out-File 默认输出 UTF-16 LE('unicode'),很多工具读不了;显式加 -Encoding utf8 即可解决。PowerShell 7 把默认值改成了 utf8NoBOM,所以同一脚本在不同机器上行为不同。其他常用值:ascii 兼容老系统,utf8NoBOM 适合 Linux 场景,oem 使用控制台代码页。

03风险

风险低风险
使用条件PowerShell
!注意: Windows PowerShell 5.1 的 utf8 编码会写入 BOM,部分 Unix 工具不识别;需要无 BOM 时用 PowerShell 7 的 utf8NoBOM 或 .NET 的 [IO.File]::WriteAllLines。

04撤销

撤销
$ Remove-Item 'C:\Temp\list.txt'

05来源

  • Out-File | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents Out-File -Encoding with values including utf8, utf8NoBOM, ascii, and unicode, and notes the default encoding differs between Windows PowerShell and PowerShell 7.
  • Out-File - PowerShell
    SS64 · technical · 2026-09-17
    依据: SS64 lists the -Encoding parameter values and explains that '>' in PowerShell is an alias for Out-File.

最后验证: 2026-09-17 · 分类: 文件与文件夹

06相关方案