PowerShell - Change file encoding (recursively)
Sometimes you face the problem that your files have the wrong encoding. If your machine got PowerShell, which is quite often the case, this is really easy.
For example: You want to change the encoding of every .java file in the current directory and all subdirectories from utf-8 to iso-8859-1:
Get-ChildItem . -include *.java -recurse | ForEach-Object {
$inputEncoding = [System.Text.Encoding]::GetEncoding("utf-8")
$outputEncoding = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$content = [System.IO.File]::ReadAllText($_.Fullname, $inputEncoding)
[System.IO.File]::WriteAllText($_.Fullname, $content, $outputEncoding)
}
In variable $inputEncoding
we set the encoding of all source files. With $outputEncoding
you can set the encoding
which you want to convert into. You can see valid encoding names in table: http://msdn.microsoft.com/en-us/library/86hf4sb8.aspx.
The Get-ChildItem
is somewhat like the find
command on Unix. With Get-Help Get-ChildItem
you can see further
information how you can find files to achieve a more specific search.