Out-File似乎在使用UTF-8时强制BOM:

$MyFile = Get-Content $MyPath
$MyFile | Out-File -Encoding "UTF8" $MyPath

我怎么能写一个文件在UTF-8没有BOM使用PowerShell?

更新2021

自从10年前我写这个问题以来,PowerShell已经发生了一些变化。检查下面的多个答案,它们有很多有用的信息!


当前回答

使用.NET的UTF8Encoding类并将$False传递给构造函数似乎是可行的:

$MyRawString = Get-Content -Raw $MyPath
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines($MyPath, $MyRawString, $Utf8NoBomEncoding)

其他回答

从版本6开始,powershell支持UTF8NoBOM编码用于设置内容和输出文件,甚至将其用作默认编码。

所以在上面的例子中,它应该是这样的:

$MyFile | Out-File -Encoding UTF8NoBOM $MyPath

可以使用下面得到UTF8没有BOM

$MyFile | Out-File -Encoding ASCII

目前正确的方法是使用@Roman Kuzmin在给@M的评论中推荐的解决方案。达德利回答:

[IO.File]::WriteAllLines($filename, $content)

(我还通过去掉不必要的系统名称空间说明来缩短了它——默认情况下它将自动被替换。)

老问题,新答案:

虽然“旧的”powershell写一个BOM,但新的平台不可知的变体确实表现不同:默认是“无BOM”,它可以通过switch配置:

-Encoding Specifies the type of encoding for the target file. The default value is utf8NoBOM. The acceptable values for this parameter are as follows: ascii: Uses the encoding for the ASCII (7-bit) character set. bigendianunicode: Encodes in UTF-16 format using the big-endian byte order. oem: Uses the default encoding for MS-DOS and console programs. unicode: Encodes in UTF-16 format using the little-endian byte order. utf7: Encodes in UTF-7 format. utf8: Encodes in UTF-8 format. utf8BOM: Encodes in UTF-8 format with Byte Order Mark (BOM) utf8NoBOM: Encodes in UTF-8 format without Byte Order Mark (BOM) utf32: Encodes in UTF-32 format.

来源:https://learn.microsoft.com/de-de/powershell/module/Microsoft.PowerShell.Utility/Out-File?view=powershell-7 我特别强调

对于PowerShell 5.1,启用此设置:

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

然后输入PowerShell:

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

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

https://github.com/PowerShell/PowerShell