Powershell: Setting Encoding for Get-Content Pipeline

Viewed 91197

I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:

cat tmp.log -encoding UTF8 > new.log

The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?

5 Answers

As suggested here:

Get-Content tmp.log | Out-File -Encoding UTF8 new.log

I would do it like this:

get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8

My understanding is that the -encoding option selects the encdoing that the file should be read or written in.

PowerShell's get-content/set-content encoding flag doesn't handle all encoding types. You may need to use IO.File, for example to load a file using Windows-1252:

$myString = [IO.File]::ReadAllText($filePath, [Text.Encoding]::GetEncoding(1252))

Text.Encoding::GetEncoding Text.Encoding::GetEncodings

Related