Set the encoding to ANSI in PowerShell 2.0
Asked Answered
S

3

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
Spiritism answered 8/6, 2016 at 10:42 Comment(0)
A
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"
Abcoulomb answered 8/6, 2016 at 11:37 Comment(3)
I've tried this one but when I open the output file I see that it's encoded in UCS-2 littleEndianSpiritism
@ZakariaBelghiti That's clearly not possible. Please provide evidence.Abcoulomb
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.Labyrinthine
B
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.

Boehm answered 8/6, 2016 at 11:2 Comment(4)
It didn't work, it says that the parameter -raw couldn't be found, maybe it's not supported in PowerShell 2.0Spiritism
ah okay, try to use the get-content without itBoehm
what encoding do you get?Boehm
UCS-2 littleEndianSpiritism
N
0

The question actually works. Note that ANSI is not ASCII, but is windows-1252 encoding https://en.wikipedia.org/wiki/Windows-1252 (see also iso-8859-1). It doesn't have a BOM. This is the powershell 5.1 default (with some exceptions like out-file or ">", which is utf16). Powershell 7 defaults to utf8 no bom.

echo á | set-content foo -Encoding Default
cat foo
á


echo á | set-content foo -Encoding ascii
cat foo
?
Napiform answered 22/9, 2023 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.