Set the encoding to ANSI in PowerShell 2.0

28,232

Solution 1

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"

Solution 2

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.

Share:
28,232
Zakaria Belghiti
Author by

Zakaria Belghiti

Hello friends, I am a computer engineering student at ENSAT, web developer, passionate about new technologies, and an ambitious guy aspiring to enrich the world.

Updated on June 09, 2020

Comments

  • Zakaria Belghiti
    Zakaria Belghiti almost 4 years

    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
    
  • Zakaria Belghiti
    Zakaria Belghiti almost 8 years
    It didn't work, it says that the parameter -raw couldn't be found, maybe it's not supported in PowerShell 2.0
  • Martin Brandl
    Martin Brandl almost 8 years
    ah okay, try to use the get-content without it
  • Martin Brandl
    Martin Brandl almost 8 years
    what encoding do you get?
  • Zakaria Belghiti
    Zakaria Belghiti almost 8 years
    I've tried this one but when I open the output file I see that it's encoded in UCS-2 littleEndian
  • Zakaria Belghiti
    Zakaria Belghiti almost 8 years
    UCS-2 littleEndian
  • Ansgar Wiechers
    Ansgar Wiechers almost 8 years
    @ZakariaBelghiti That's clearly not possible. Please provide evidence.