PoshCode Archive  Artifact [ef51b41a6c]

Artifact ef51b41a6c19599991ab5cf3d84af338469c9bb56497df030e23816f185eaa9a:

  • File Get-FileEncoding.ps1 — part of check-in [ac1ac64f4f] at 2018-06-10 14:11:29 on branch trunk — Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM). (user: Chad Miller size: 1503)

# encoding: ascii
# api: powershell
# title: Get-FileEncoding
# description: Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
# version: 0.1
# type: script
# author: Chad Miller
# license: CC0
# function: Get-FileEncoding
# x-poshcode-id: 6249
# x-derived-from-id: 6250
# x-archived: 2017-05-17T23:51:19
# x-published: 2017-03-13T22:14: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://stackoverflow.com/questions/3825390/effective-way-to-find-any-files-encoding
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne '65001'}
This command gets ps1 files in current directory where encoding codepage is not 65001
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne '65001'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding 65001}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
    [CmdletBinding()] Param (
     [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
    )

   process {
	$File = New-Object System.IO.StreamReader -arg $Path, defaultEncodingIfNoBom
	$null = $File.Peek()
	$encoding = FileContents.CurrentEncoding.Codepage
	$return $encoding
}
}