@@ -81,7 +81,59 @@ function Get-InvalidOperationRecord
8181 return New-Object @newObjectParams
8282}
8383
84+ <#
85+ . SYNOPSIS
86+ Gets file encoding. Defaults to ASCII.
87+
88+ . DESCRIPTION
89+ The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
90+ Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
91+
92+ . EXAMPLE
93+ Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
94+ This command gets ps1 files in current directory where encoding is not ASCII
95+
96+ . EXAMPLE
97+ Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | `
98+ foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
99+ Same as previous example but fixes encoding using set-content
100+ #>
101+ function Get-FileEncoding
102+ {
103+ [CmdletBinding ()]
104+ [OutputType ([System.String ])]
105+ param
106+ (
107+ [Parameter (Mandatory = $true , ValueFromPipelineByPropertyName = $true )]
108+ [System.String ]
109+ $Path
110+ )
111+
112+ [System.Byte []] $byte = Get-Content - Encoding byte - ReadCount 4 - TotalCount 4 - Path $Path
113+
114+ if ($byte [0 ] -eq 0xef -and $byte [1 ] -eq 0xbb -and $byte [2 ] -eq 0xbf )
115+ {
116+ return ' UTF8'
117+ }
118+ elseif ($byte [0 ] -eq 0xff -and $byte [1 ] -eq 0xfe )
119+ {
120+ return ' UTF32'
121+ }
122+ elseif ($byte [0 ] -eq 0xfe -and $byte [1 ] -eq 0xff )
123+ {
124+ return ' BigEndianUnicode'
125+ }
126+ elseif ($byte [0 ] -eq 0 -and $byte [1 ] -eq 0 -and $byte [2 ] -eq 0xfe -and $byte [3 ] -eq 0xff )
127+ {
128+ return ' BigEndianUTF32'
129+ }
130+ else
131+ {
132+ return ' ASCII'
133+ }
134+ }
135+
84136Export-ModuleMember - Function `
85137 ' Get-InvalidArgumentRecord' , `
86- ' Get-InvalidOperationRecord'
87-
138+ ' Get-InvalidOperationRecord' , `
139+ ' Get-FileEncoding '
0 commit comments