0

Just can't get ASCII encoding get to work in PowerShell. Tried a bunch of different approaches.

Whatever I try I get an UTF8 encoded file (that is what NPP tells me):

$newLine = "Ein Test öäü"
$newLine | Out-File -FilePath "c:\temp\check.txt"  -Encoding ascii

PSVersion = 5.1.14393.5066

Any hint is welcome!

phuclv
  • 37,963
  • 15
  • 156
  • 475

2 Answers2

3

ASCII is a 7-bit character set and doesn't contain any accented character, so obviously storing öäü in ASCII doesn't work. If you need UTF-8 then you need to specify encoding as utf8

$newLine = "Ein Test öäü"
$newLine | Out-File -FilePath "c:\temp\check.txt" -Encoding utf8

If you need another encoding then specify it accordingly. For example to get the ANSI code page use this

$newLine = "Ein Test öäü"
$newLine | Out-File -FilePath "c:\temp\check.txt" -Encoding default

-Encoding default will save the file in the current ANSI code page and -Encoding oem will use the current OEM code page. Just press Tab after -Encoding and PowerShell will cycle through the list of supported encodings. For encodings not in that list you can trivially deal with them using System.Text.Encoding

Note that "ANSI code page" is a misnomer and the actual encoding changes depending on each environment so it won't be reliable. For example if you change the code page manually then it won't work anymore. For a more reliable behavior you need to explicitly specify the encoding (typically Windows-1252 for Western European languages). In older PowerShell use

[IO.File]::WriteAllLines("c:\temp\check.txt", $newLine, [Text.Encoding]::GetEncoding(1252)

and in PowerShell Core you can use

$newLine | Out-File -FilePath "check2.txt" -Encoding ([Text.Encoding]::GetEncoding(1252))

See How do I change my Powershell script so that it writes out-file in ANSI - Windows-1252 encoding?

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 1
    Nice! I would just add that for PS 5.1 the script file must be saved in UTF-8-with-BOM encoding. – zett42 May 29 '22 at 18:30
  • I need obligatory ASCII, and unfortunately, even when I do $newLine = "Test with 7 bit only" $newLine | Out-File -FilePath "c:\temp\check.txt" -Encoding ascii I get an UTF-8 file instead of an ascii file!! – Stefan Gasteiger Jun 01 '22 at 08:59
  • I found out when reading the raw bytes: ANSI: ö --> 246 UTF8: ö --> 195 182 Can I force PowerShell to create ANSI? – Stefan Gasteiger Jun 01 '22 at 09:52
  • @StefanGasteiger obviously. You can specify any encoding you want. But note that there's no such thing as "ANSI". `ö` is code point 246 in ISO-8859-1 and Windows 1252 which are the default encodings on Western locales – phuclv Jun 01 '22 at 14:44
0

Found the solution:

$file    = "c:\temp\check-ansi.txt"
$newLine = "Ein Test öÖäÄüÜ"
   
Remove-Item $file
[IO.File]::WriteAllLines($file, $newLine, [Text.Encoding]::GetEncoding(28591))