Using PowerShell to write a file in UTF-8 without the BOM

前端 未结 13 1354
名媛妹妹
名媛妹妹 2020-11-22 06:25

Out-File seems to force the BOM when using UTF-8:

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

13条回答
  •  轮回少年
    2020-11-22 07:15

    When using Set-Content instead of Out-File, you can specify the encoding Byte, which can be used to write a byte array to a file. This in combination with a custom UTF8 encoding which does not emit the BOM gives the desired result:

    # This variable can be reused
    $utf8 = New-Object System.Text.UTF8Encoding $false
    
    $MyFile = Get-Content $MyPath -Raw
    Set-Content -Value $utf8.GetBytes($MyFile) -Encoding Byte -Path $MyPath
    

    The difference to using [IO.File]::WriteAllLines() or similar is that it should work fine with any type of item and path, not only actual file paths.

提交回复
热议问题