2014-07-24 3 views
1

하나의 폴더에 여러 텍스트 파일의 인코딩을 나열하고이를 powershell의 별도 텍스트 파일로 출력하려고합니다. 다음 함수를 사용하여 인코딩을 식별합니다. 각 파일의 헤더를 검사 : -powershell에서 .txt 인코딩보기

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' } 
    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'} 
    else 
    { Write-Output 'ASCII' } 

내가 다음 코드에서 그것을 사용하고이 위치에있는 모든 .txt 인 파일에 대해 그것을 실행 :

Get-ChildItem *.txt | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} 

유일한 문제는이입니다 유니 코드/UTF8로 알려진 파일조차도 모든 파일에 대해 ASCII를 반환합니다. 내가 파일 이름과 실제 내용이 아닌 단지 그것을 실행하는 것처럼 정말 바보 같은 일을하고 있는가?

답변

0

당신은 그것을 변경해야

if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) 
    { Write-Output 'UTF8' } 

    # FE FF (UTF-16 Big-Endian) 
    elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) 
    { Write-Output 'Unicode UTF-16 Big-Endian' } 

    # FF FE (UTF-16 Little-Endian) 
    elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe) 
    { Write-Output 'Unicode UTF-16 Little-Endian' } 

    # 00 00 FE FF (UTF32 Big-Endian) 
    elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) 
    { Write-Output 'UTF32 Big-Endian' } 

here.

+0

최고 사용할 수있는 기능에 대한 자세한 버전이있다! 빠른 응답을 주셔서 감사합니다. 이제 완벽하게 작동합니다! – YetiFiasco

관련 문제