Skip to content

Instantly share code, notes, and snippets.

@zommarin
Created December 15, 2011 12:43
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zommarin/1480974 to your computer and use it in GitHub Desktop.
Save zommarin/1480974 to your computer and use it in GitHub Desktop.
Get-FileEncoding
function Get-FileEncoding($Path) {
$bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)
if(!$bytes) { return 'utf8' }
switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
'^efbbbf' { return 'utf8' }
'^2b2f76' { return 'utf7' }
'^fffe' { return 'unicode' }
'^feff' { return 'bigendianunicode' }
'^0000feff' { return 'utf32' }
default { return 'ascii' }
}
}
@mac2000
Copy link

mac2000 commented Nov 18, 2015

Thanks for your code, but it not always shows truth.

Got working sample: https://github.com/mac2000/WindowsPowerShell/blob/master/Modules/Is-UTF8/Is-UTF8.psm1

Idea from: https://github.com/madx/moreutils/blob/master/isutf8.c

Downside that it will work only with small files.

@JohnLBevan
Copy link

Thank-you for sharing; this is really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment