Skip to content

Instantly share code, notes, and snippets.

@punitganshani
Last active August 29, 2015 14:25
Show Gist options
  • Save punitganshani/b08d8d14eeb5516934ae to your computer and use it in GitHub Desktop.
Save punitganshani/b08d8d14eeb5516934ae to your computer and use it in GitHub Desktop.
Get Encoding of Files [PowerShell]
function Get-FileEncodingOfFilesInFolder
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path, [string]$pattern
)
$files = Get-ChildItem -path $Path $pattern -Recurse | Select-Object FullName
$encodings = @{}
$encodingMembers = [System.Text.Encoding] | Get-Member -Static -MemberType Property
$encodingMembers | Foreach-Object {
$encodingBytes = [System.Text.Encoding]::($_.Name).GetPreamble() -join '-'
$encodings[$encodingBytes] = $_.Name
}
$encodingLengths = $encodings.Keys | Where-Object { $_ } | Foreach-Object { ($_ -split "-").Count }
$counter = 0
$files | ForEach-Object {
$counter= $counter+1
$result = "UTF7"
$file = $_
$completed = $counter / $files.Count
Write-Progress -Activity "Encoding detection" -status "$($counter) / $($files.count) Complete"
$found=$false
foreach($encodingLength in $encodingLengths | Sort -Descending)
{
$content = Get-Content $file.FullName -encoding byte -readcount $encodingLength
$bytes = $content[0]
$encoding = $encodings[$bytes -join '-']
if($encoding)
{
$result = $encoding
Write-Output "$($file.FullName): $([System.Text.Encoding]::$result)"
$found=$true
break
}
}
if ($found -eq $false){
Write-Output "$($file.FullName): UNRECOGNIZED"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment