Saving Text Files without BOM

by Mar 12, 2021

On Windows, by default many cmdlets encode text files with a BOM (Byte Order Mask) encoding. BOM writes some extra bytes at the beginning of a text file to mark the encoding used to write the file.

Unfortunately, BOM encoding wasn’t adopted well outside the Windows world. Today, when you save a text file on a Windows system and upload it to i.e. GitHub, the BOM encoding can corrupt the file or make it entirely unreadable.

Here is some code that can be used to make sure text files are saved without BOM in a way compatible with Linux:

$outpath = "$env:temp\nobom.txt"
$text = 'This is the text to write to disk.'
$Utf8NoBomEncoding = [System.Text.UTF8Encoding]::new($false)
[System.IO.File]::WriteAllLines($outpath, $text, $Utf8NoBomEncoding)
$outpath


Twitter This Tip! ReTweet this Tip!