|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | + Determines the encoding of a file. |
| 4 | +
|
| 5 | +.DESCRIPTION |
| 6 | + The Get-FileEncoding function determines the encoding of a file by examining the file's byte order mark (BOM) or by checking if the file is ASCII or UTF8 without BOM. |
| 7 | +
|
| 8 | +.PARAMETER Path |
| 9 | + Specifies the path of the file to check. |
| 10 | +
|
| 11 | +.EXAMPLE |
| 12 | + Get-FileEncoding -Path "C:\path\to\file.txt" |
| 13 | + Returns the encoding of the specified file. |
| 14 | +
|
| 15 | +.OUTPUTS |
| 16 | + System.String |
| 17 | + The function returns a string representing the encoding of the file. Possible values are: |
| 18 | + - UTF8-BOM: UTF-8 encoding with a byte order mark (BOM). |
| 19 | + - Unicode: UTF-16 encoding (little-endian). |
| 20 | + - BigEndianUnicode: UTF-16 encoding (big-endian). |
| 21 | + - UTF7: UTF-7 encoding. |
| 22 | + - UTF32: UTF-32 encoding. |
| 23 | + - UTF8: UTF-8 encoding without a byte order mark (BOM). |
| 24 | + - ASCII: ASCII encoding. |
| 25 | +
|
| 26 | +.NOTES |
| 27 | + This function requires PowerShell version 3.0 or later. |
| 28 | +#> |
| 29 | + |
| 30 | +function Get-FileEncoding() |
| 31 | +{ |
| 32 | + param ( |
| 33 | + [string]$Path = '' |
| 34 | + ); |
| 35 | + |
| 36 | + if ([string]::IsNullOrEmpty($Path) -Or (Test-Path -Path $Path) -eq $FALSE) { |
| 37 | + Write-IcingaConsoleError 'The specified file "{0}" was not found' -Objects $Path; |
| 38 | + return $null; |
| 39 | + } |
| 40 | + |
| 41 | + $Bytes = Get-Content -Encoding Byte -ReadCount 4 -TotalCount 4 -Path $Path; |
| 42 | + |
| 43 | + if ($Bytes[0] -eq 0xef -and $Bytes[1] -eq 0xbb -and $Bytes[2] -eq 0xbf) { |
| 44 | + return 'UTF8-BOM'; |
| 45 | + } elseif ($Bytes[0] -eq 0xff -and $Bytes[1] -eq 0xfe) { |
| 46 | + return 'Unicode'; |
| 47 | + } elseif ($Bytes[0] -eq 0xfe -and $Bytes[1] -eq 0xff) { |
| 48 | + return 'BigEndianUnicode'; |
| 49 | + } elseif ($Bytes[0] -eq 0x2b -and $Bytes[1] -eq 0x2f -and $Bytes[2] -eq 0x76) { |
| 50 | + return 'UTF7'; |
| 51 | + } elseif ($Bytes[0] -eq 0xff -and $Bytes[1] -eq 0xfe -and $Bytes[2] -eq 0x00 -and $Bytes[3] -eq 0x00) { |
| 52 | + return 'UTF32'; |
| 53 | + } else { |
| 54 | + # Check if the file is ASCII or UTF8 without BOM |
| 55 | + $Content = Get-Content -Encoding String -Path $Path; |
| 56 | + $Bytes = [System.Text.Encoding]::UTF8.GetBytes($content); |
| 57 | + |
| 58 | + # Check each byte to see if it's outside the ASCII range |
| 59 | + foreach ($byte in $Bytes) { |
| 60 | + if ($byte -gt 127) { |
| 61 | + return 'UTF8'; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + # This is the default encoding, as UTF8 without BOM could be valid ASCII |
| 67 | + return 'ASCII'; |
| 68 | +} |
0 commit comments