Why does this Powershell command always result in a different file encoding?

If file1.txt is encoded in ANSI, and this command is run:

powershell -Command "(gc file1.txt) -replace 'foo', 'bar' | Out-File file2.txt"

then file2.txt is always encoded in UCS-2 LE BOM.

Why, and how can I specify the output to be ANSI encoded?

2 answers

  • answered 2017-06-17 18:36 RockPaperLizard

    Use -enconding Ascii to ensure the output file is ASCII.

    The command will be:

    powershell -Command "(gc file1.txt) -replace 'foo', 'bar' | Out-File -Encoding Ascii file2.txt"

  • answered 2017-06-17 18:36 restless1987

    You could also go ahead and use Set-Content. This seems to keep the encoding in the file, so you dont have to worry about, what enconding might be correct.

    powershell -Command "(gc file1.txt) -replace 'foo', 'bar' | Set-Content file2.txt"