Last active
July 12, 2018 12:50
-
-
Save martea/a87b662dac4d8c28e888c09f134cef90 to your computer and use it in GitHub Desktop.
Convert files to specific encoding with converting, solving special chars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -typedef @" | |
public class EncodingHelper | |
{ | |
public static System.Text.Encoding GetEncoding(string file) | |
{ | |
System.Text.Encoding encoding; | |
using (var reader = new System.IO.StreamReader(file, System.Text.Encoding.Default, true)) | |
{ | |
reader.Peek(); // you need this! | |
encoding = reader.CurrentEncoding; | |
} | |
return encoding; | |
} | |
public static string ConvertFile(string file, System.Text.Encoding targetEncoding) | |
{ | |
var sourceContent = System.IO.File.ReadAllBytes(file); | |
var sourceEncoding = GetEncoding(file); | |
return targetEncoding.GetString(System.Text.Encoding.Convert(sourceEncoding, targetEncoding, sourceContent)); | |
} | |
} | |
"@ | |
function Convert-To-Encoding([String]$filter, [System.Text.Encoding]$encoding) { | |
Get-ChildItem -Recurse -Filter $filter | ForEach-Object { | |
write-host "Start.... $($_.FullName)" | |
$data = [EncodingHelper]::ConvertFile($_.FullName, $encoding) | |
write-host "Converted..." | |
[System.IO.File]::WriteAllLines($_.FullName, $data, $encoding) | |
write-host "Written... " | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage. run file, then use method "Convert-To-Encoding" provide filter and encoding