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

前端 未结 13 1366
名媛妹妹
名媛妹妹 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:03

        [System.IO.FileInfo] $file = Get-Item -Path $FilePath 
        $sequenceBOM = New-Object System.Byte[] 3 
        $reader = $file.OpenRead() 
        $bytesRead = $reader.Read($sequenceBOM, 0, 3) 
        $reader.Dispose() 
        #A UTF-8+BOM string will start with the three following bytes. Hex: 0xEF0xBB0xBF, Decimal: 239 187 191 
        if ($bytesRead -eq 3 -and $sequenceBOM[0] -eq 239 -and $sequenceBOM[1] -eq 187 -and $sequenceBOM[2] -eq 191) 
        { 
            $utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False) 
            [System.IO.File]::WriteAllLines($FilePath, (Get-Content $FilePath), $utf8NoBomEncoding) 
            Write-Host "Remove UTF-8 BOM successfully" 
        } 
        Else 
        { 
            Write-Warning "Not UTF-8 BOM file" 
        }  
    

    Source How to remove UTF8 Byte Order Mark (BOM) from a file using PowerShell

提交回复
热议问题