Posted On December 2, 2020

PowerShell: Check File Encoding UTF7, UTF8, UTF16, UTF32, ASCII

kimconnect 0 comments
blog.KimConnect.com >> Windows >> PowerShell: Check File Encoding UTF7, UTF8, UTF16, UTF32, ASCII
$filePath='C:\Windows\System32\Drivers\etc\hosts'

function getFileEncoding($filePath) {
	# Checking the byte order mark (BOM) or first 4 bytes
    $bom = [byte[]](Get-Content $filePath -Encoding byte -ReadCount 4 -TotalCount 4)
    if(!$bom) { # case: UTF-8 without BOM
    	return 'utf8'
    }else{
    	switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bom[0],$bom[1],$bom[2],$bom[3]) {
        	'^2b2f76'   { return 'UTF-7' } # endianless
	       	'^efbbbf'   { return 'UTF-8' } # endianless
			'^fffe'     { return 'UTF-16-LE' } #little endian
        	'^feff'     { return 'UTF-16-BE' } #big endian
			'^fffe0000' { return 'UTF-32-LE' } #little endian
			'^0000feff' { return 'UTF-32-BE' } #big endian
        	default     { return 'ASCII' }
    	}
    }
}

getFileEncoding $filePath

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Microsoft Exchange to Require that all Senders are Authenticated

In this scenario, the business decision is to limit exposure of certain internal accounts to…

PowerShell: Set Windows Scheduled Task to Send a Pop-up Message

# Set variables $taskName='Bi-weekly Meeting Reminder' $time='11:50am' $daily=New-ScheduledTaskTrigger -Daily -At $time $everyOtherDay=New-ScheduledTaskTrigger -Daily -DaysInterval 2…

Find Empty Directories

$directories="\\FILESERVER01\SHARE01" # Dynamic Credential method 1 $who = whoami if ($who.substring($who.length-2, 2) -eq "-admin"){$username=$who;} else…