Is there any way to omit the byte-order mark when redirecting the output stream to a file? For example, if I want to take the contents of an XML file and replace a string with a new value, I need to do create a new encoding and write the new output to a file like the following which is rather ham-handed:
$newContent = ( Get-Content .\settings.xml ) -replace 'expression', 'newvalue'
$UTF8NoBom = New-Object System.Text.UTF8Encoding( $false )
[System.IO.File]::WriteAllText( '.\settings.xml', $newContent, $UTF8NoBom )
I have also tried using Out-File
, but specifying UTF8
as the encoding still contains a BOM:
( Get-Content .\settings.xml ) -replace 'expression', 'newvalue' | Out-File -Encoding 'UTF8' .\settings.xml
What I want to be able to do is simply redirect to a file without a BOM:
( Get-Content .\settings.xml ) -replace 'expression, 'newvalue' > settings.xml
The problem is that the BOM which is added to the output file routinely cause issues when reading these files from other applications (most notably, most applications which read an XML blow up if I modify the XML and it begins with a BOM, Chef Client also doesn't like a BOM in a JSON attributes file). Short of me writing a function like Write-FileWithoutBom
to accept pipeline input and an output path, is there any way I can simply "turn off" writing a BOM when redirecting output to a file?
The solution doesn't necessarily have to use the redirection operator. If there is a built-in cmdlet I can use to output to a file without a BOM, that would be acceptable as well.
Powershell Core
does support this, so it hopefully meansMicrosoft Powershell 6.0
will also support it. – Bigford