I wrote a small file joining program with some functionality, all works fine, but I have to set encoding of output file to utf8 without bom. I tried to add on the beginning of program this line "$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'" but result was that I've got a utf8 with bom. I've tried to use -Encoding utf8NoBOM but not work(I've got error).I Work on PS Version 5.What I should do to get UTF8 without bom?
Asked
Active
Viewed 375 times
1 Answers
1
If you are using PowerShell version 7.X, you can simply add parameter -Encoding utf8NoBOM
to Add-Content
.
If your version is below 7.X, you could use this:
# The StreamWriter class by default uses Utf8 without BOM encoding
# get a StreamWriter to a new or existing file to append text to
$streamWriter = [System.IO.File]::AppendText('D:\Test\Blah.txt')
# or if you want to overwrite an existing file, use this
# $streamWriter = [System.IO.File]::CreateText('D:\Test\Blah.txt')
# or this:
# $streamWriter = [System.IO.StreamWriter]::new('D:\Test\Blah.txt', $true) # $true for Append
Next write your content using this instead of Add-Content
$streamWriter.WriteLine("blah something that needs UTF8: €")
And when all writing is done, close the file and release the StreamWriter object
$streamWriter.Dispose()

Theo
- 57,719
- 8
- 24
- 41