# encoding: ascii
# api: powershell
# title: Get-FileEncoding
# description: Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
# version: 1.0
# type: script
# author: JasonMArcher
# license: CC0
# function: Get-FileEncoding
# x-poshcode-id: 5724
# x-derived-from-id: 5725
# x-archived: 2015-05-06T20:46:17
# x-published: 2015-02-04T00:50:00
#
#
<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.OUTPUT
System.Text.Encoding
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {[string]$_.Encoding -ne 'System.Text.ASCIIEncoding'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {[string]$_.Encoding -ne 'System.Text.ASCIIEncoding'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
.NOTES
Version History
v1.0 - 2010/08/10, Chad Miller - Initial release
v1.1 - 2010/08/16, Jason Archer - Improved pipeline support and added detection of little endian BOMs.
v1.2 - 2015/02/03, VertigoRay - Adjusted to use .NET's System.Text.Encoding Class (https://msdn.microsoft.com/library/System.Text.Encoding(v=vs.110).aspx)
.LINK
http://blog.vertigion.com/post/110022387292/powershell-get-fileencoding
#>
function Get-FileEncoding {
[CmdletBinding()]
param (
[Alias("PSPath")]
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[String]$Path
)
process {
[Byte[]]$bom = Get-Content -Encoding Byte -ReadCount 4 -TotalCount 4 -Path $Path
$encoding_found = $false
foreach ($encoding in [System.Text.Encoding]::GetEncodings().GetEncoding()) {
$preamble = $encoding.GetPreamble()
if ($preamble) {
foreach ($i in 0..$preamble.Length) {
if ($preamble[$i] -ne $bom[$i]) {
break
} elseif ($i -eq $preable.Length) {
$encoding_found = $encoding
}
}
}
}
if (!$encoding_found) {
# $encoding_found = [System.Text.Encoding]::Default
$encoding_found = [System.Text.Encoding]::ASCII
}
$encoding_found
}
}