如何在PowerShell中生成无BOM的UTF-8格式TXT文件?
生成无BOM的UTF-8格式TXT文件(PowerShell)
根据PowerShell版本不同,有两种可靠的解决方法:
1. PowerShell 6及以上版本
直接使用utf8NoBOM编码参数即可,这是官方新增的无BOM UTF-8选项:
"Text" | Out-File .\File.txt -Encoding utf8NoBOM
也可以用Set-Content搭配该参数,效果一致:
Set-Content .\File.txt -Value "Text" -Encoding utf8NoBOM
2. PowerShell 5.1及更早版本(Windows默认预装版本)
由于旧版本PowerShell没有原生的无BOM UTF-8编码参数,可直接调用.NET类库的方法实现:
[System.IO.File]::WriteAllText("$PWD\File.txt", "Text", [System.Text.Encoding]::UTF8)
这里的.NET System.Text.Encoding::UTF8默认就是无BOM的UTF-8,和PowerShell自带的-Encoding utf8(带BOM)是不同的实现。
内容的提问来源于stack exchange,提问作者Christopher Cass
相关产品推荐
相关产品推荐

