3

I want to set the encoding of a file to ANSI using the parameter -Encoding of the Set-Content cmdlet, I tried this one but it didn't work:

Set-Content -LiteralPath "$filePath" -Encoding Default
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Zakaria Belghiti
  • 521
  • 3
  • 8
  • 19

2 Answers2

10

PowerShell v2 doesn't recognize an argument Default for the parameter -Encoding. Use the argument Ascii to save a file with ANSI encoding:

Set-Content -LiteralPath "$filePath" -Encoding Ascii

or omit the parameter entirely (Set-Content defaults to ANSI encoding):

Set-Content -LiteralPath "$filePath"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I've tried this one but when I open the output file I see that it's encoded in UCS-2 littleEndian – Zakaria Belghiti Jun 08 '16 at 11:40
  • 1
    @ZakariaBelghiti That's clearly not possible. Please provide evidence. – Ansgar Wiechers Jun 08 '16 at 11:50
  • Not sure if there is a way around but I get the following message: `Set-Content : Cannot process command because of one or more missing mandatory parameters: Value.` I only want to change encoding not the content. Is there a different command. – Matt Fricker Jan 27 '23 at 14:27
1

I use the .NET WriteAllText function for that:

[IO.File]::WriteAllText($filePath, (Get-Content $filePath))

Ensure the default encoding reflects your desired output using:

[System.Text.Encoding]::Default

Otherwise, add the enum with the desired encoding as the third parameter.

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172