File code page conversion (Powershell)

Today I needed to convert few files from Windows-1250 code page to something reasonable (which means UTF-8 :)) and I decided to write a Powershell script for it. Oddly enough, I was not able to do that in “pure” Powershell – it’s because I work on US Windows (CP-1252) and I didn’t succeed in imposing another code page to Powershell. The chcp command didn’t help either.

Finally I simply called few .NET methods from Powershell and the problem is resolved.

$encoding = [System.Text.Encoding]::GetEncoding($encodingCode)
$text = [System.IO.File]::ReadAllText($inputFile, $encoding)
[System.IO.File]::WriteAllText($outputFile, $text)

$inputFile and $outputFile contain file names (it can be even a single file) and $encodingCode is code page of the source file (1250 in my case). The output file is in a default encoding, which is just UTF-8.