1

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?

Rob
  • 13
  • 3
  • 1
    UTF-8 doesn't need a BOM. – Raedwald Aug 27 '21 at 11:21
  • @Raedwald I know but, and i want to got this. If i run my script and after that check the outfile encoding(in notepad) i see UTF-8 with bom, and i want to get utf-8 without bom – Rob Aug 27 '21 at 11:24

1 Answers1

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