PoshCode Logo PowerShell Code Repository

Get-FileEncoding by Chad Miller 6 years ago
View followups from JasonMArcher, RyanFisher, Enter your zip code here, Billy and 281269281 | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2059"></script>download | new post

Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).

  1. <#
  2. .SYNOPSIS
  3. Gets file encoding.
  4. .DESCRIPTION
  5. The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
  6. Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
  7. .EXAMPLE
  8. Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
  9. This command gets ps1 files in current directory where encoding is not ASCII
  10. .EXAMPLE
  11. Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
  12. Same as previous example but fixes encoding using set-content
  13. #>
  14. function Get-FileEncoding
  15. {
  16.     [CmdletBinding()] Param (
  17.      [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
  18.     )
  19.  
  20.     [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
  21.  
  22.     if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
  23.     { Write-Output 'UTF8' }
  24.     elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
  25.     { Write-Output 'Unicode' }
  26.     elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
  27.     { Write-Output 'UTF32' }
  28.     elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
  29.     { Write-Output 'UTF7'}
  30.     else
  31.     { Write-Output 'ASCII' }
  32. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me