Skip to content

Instantly share code, notes, and snippets.

@matma
Last active December 23, 2015 21:39
Show Gist options
  • Save matma/6698082 to your computer and use it in GitHub Desktop.
Save matma/6698082 to your computer and use it in GitHub Desktop.
Converts files to UTF8
function Get-FileEncoding
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
)
[byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ Write-Output 'UTF8 BOM' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ Write-Output 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ Write-Output 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ Write-Output 'UTF7'}
elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe )
{ Write-Output '1200' }
elseif( $byte[0] -eq 0x3c -and $byte[1] -eq 0x25 -and $byte[2] -eq 0x40 )
{ Write-Output 'UTF8' }
else
{ Write-Output 'ASCII' }
}
function ChangeEncoding ($baseDirectory)
{
$allFiles = Get-ChildItem $baseDirectory -include *.aspx -recurse | where-object { -not $_.PSIsContainer }
foreach( $file in $allFiles){
$encoding = Get-FileEncoding $file.FullName
if( "UTF8 BOM" -ne $encoding ) {
if( "1200" -eq $encoding ) {
$rawContent = get-content $file.FullName -encoding byte
$fileContent = [System.Text.Encoding]::GetEncoding(1200).GetString($rawContent)
$fileContent | set-content -encoding utf8 $file.FullName -force
} else {
$fileContent = get-content $file.FullName -encoding $encoding -force
$fileContent | set-content -encoding utf8 $file.FullName -force
}
}
"$file --- $encoding"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment