Out-File似乎在使用UTF-8时强制BOM:
$MyFile = Get-Content $MyPath
$MyFile | Out-File -Encoding "UTF8" $MyPath
我怎么能写一个文件在UTF-8没有BOM使用PowerShell?
更新2021
自从10年前我写这个问题以来,PowerShell已经发生了一些变化。检查下面的多个答案,它们有很多有用的信息!
Out-File似乎在使用UTF-8时强制BOM:
$MyFile = Get-Content $MyPath
$MyFile | Out-File -Encoding "UTF8" $MyPath
我怎么能写一个文件在UTF-8没有BOM使用PowerShell?
更新2021
自从10年前我写这个问题以来,PowerShell已经发生了一些变化。检查下面的多个答案,它们有很多有用的信息!
当前回答
我使用的一种技术是使用Out-File cmdlet将输出重定向到ASCII文件。
例如,我经常运行创建另一个SQL脚本并在Oracle中执行的SQL脚本。使用简单的重定向(“>”),输出将是SQLPlus无法识别的UTF-16格式。要解决这个问题:
sqlplus -s / as sysdba "@create_sql_script.sql" |
Out-File -FilePath new_script.sql -Encoding ASCII -Force
生成的脚本可以通过另一个SQLPlus会话执行,而无需担心Unicode:
sqlplus / as sysdba "@new_script.sql" |
tee new_script.log
更新:正如其他人指出的那样,这会删除非ascii字符。由于用户要求一种“强制”转换的方法,我假设他们并不关心这一点,因为他们的数据可能不包含这样的数据。
如果您关心非ascii字符的保存,这不是适合您的答案。
其他回答
可以使用下面得到UTF8没有BOM
$MyFile | Out-File -Encoding ASCII
我建议只使用Set-Content命令,不需要其他任何命令。
我系统中的powershell版本是:-
PS C:\Users\XXXXX> $PSVersionTable.PSVersion | fl
Major : 5
Minor : 1
Build : 19041
Revision : 1682
MajorRevision : 0
MinorRevision : 1682
PS C:\Users\XXXXX>
所以你需要跟随。
PS C:\Users\XXXXX> Get-Content .\Downloads\finddate.txt
Thursday, June 23, 2022 5:57:59 PM
PS C:\Users\XXXXX> Get-Content .\Downloads\finddate.txt | Set-Content .\Downloads\anotherfile.txt
PS C:\Users\XXXXX> Get-Content .\Downloads\anotherfile.txt
Thursday, June 23, 2022 5:57:59 PM
PS C:\Users\XXXXX>
现在,当我们检查文件,根据截图,它是utf8。 anotherfile.txt
使用.NET的UTF8Encoding类并将$False传递给构造函数似乎是可行的:
$MyRawString = Get-Content -Raw $MyPath
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines($MyPath, $MyRawString, $Utf8NoBomEncoding)
更改多个文件扩展到UTF-8没有BOM:
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
foreach($i in ls -recurse -filter "*.java") {
$MyFile = Get-Content $i.fullname
[System.IO.File]::WriteAllLines($i.fullname, $MyFile, $Utf8NoBomEncoding)
}
从版本6开始,powershell支持UTF8NoBOM编码用于设置内容和输出文件,甚至将其用作默认编码。
所以在上面的例子中,它应该是这样的:
$MyFile | Out-File -Encoding UTF8NoBOM $MyPath