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已经发生了一些变化。检查下面的多个答案,它们有很多有用的信息!
当前回答
对于PowerShell 5.1,启用此设置:
控制面板,区域,管理,更改系统区域,使用Unicode UTF-8 全球语言支持
然后输入PowerShell:
$PSDefaultParameterValues['*:Encoding'] = 'Default'
或者,您可以升级到PowerShell 6或更高版本。
https://github.com/PowerShell/PowerShell
其他回答
对于PowerShell 5.1,启用此设置:
控制面板,区域,管理,更改系统区域,使用Unicode UTF-8 全球语言支持
然后输入PowerShell:
$PSDefaultParameterValues['*:Encoding'] = 'Default'
或者,您可以升级到PowerShell 6或更高版本。
https://github.com/PowerShell/PowerShell
可以使用下面得到UTF8没有BOM
$MyFile | Out-File -Encoding ASCII
重要!:这只适用于当一个额外的空格或换行符在开始是没有问题的文件用例 (例如,如果是SQL文件、Java文件或人类可读的文本文件)
可以结合使用创建一个空(非utf8或ASCII (utf8兼容))文件并追加它(如果源文件是一个文件,则将$str替换为gc $src):
" " | out-file -encoding ASCII -noNewline $dest
$str | out-file -encoding UTF8 -append $dest
当一行程序
根据你的用例替换$dest和$str:
$_ofdst = $dest ; " " | out-file -encoding ASCII -noNewline $_ofdst ; $src | out-file -encoding UTF8 -append $_ofdst
作为简单函数
function Out-File-UTF8-noBOM { param( $str, $dest )
" " | out-file -encoding ASCII -noNewline $dest
$str | out-file -encoding UTF8 -append $dest
}
与源文件一起使用:
Out-File-UTF8-noBOM (gc $src), $dest
与字符串一起使用:
Out-File-UTF8-noBOM $str, $dest
可选:继续追加Out-File: "more foo bar" | Out-File -encoding UTF8 -append $dest
这个脚本将把DIRECTORY1中的所有.txt文件转换为不含BOM的UTF-8格式,并将它们输出到DIRECTORY2
foreach ($i in ls -name DIRECTORY1\*.txt)
{
$file_content = Get-Content "DIRECTORY1\$i";
[System.IO.File]::WriteAllLines("DIRECTORY2\$i", $file_content);
}
我认为这不会是UTF,但我只是发现了一个相当简单的解决方案,似乎工作…
Get-Content path/to/file.ext | out-file -encoding ASCII targetFile.ext
对我来说,这导致了一个没有bom文件的utf-8,不管源格式如何。