码迷,mamicode.com
首页 > 其他好文 > 详细

获取文件编码方式

时间:2015-05-10 22:16:51      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

if (!(Test-Path alias:gfe)) { Set-Alias gfe Get-FileEncoding }

function Get-FileEncoding {
  <#
    .NOTES
        Author: greg zakharov
  #>
  param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [ValidateScript({Test-Path $_})]
    [String]$FileName
  )
 
  begin {
    [Text.Encoding] | Get-Member -Static -MemberType Property | % {$enc = @{}}{
      if (($bytes = [Text.Encoding]::($_.Name).GetPreamble()) -ne $null) {
        $enc[$_.Name] = $bytes
      }
    }
  }
  process {
    try {
      $fs = [IO.File]::OpenRead($FileName)
      $buf = New-Object "Byte[]" $fs.Length
      [void]$fs.Read($buf, 0, $buf.Length)
     
      if (($enc = $enc.Keys | ? {
        foreach ($arr in ($buf[0..1], $buf[0..2], $buf[0..3])) {
          (Compare-Object $enc[$_] $arr -SyncWindow 0) -eq $null
        }
      }).Length -eq 2) { $enc = ‘UTF32‘ }
      if ($enc -eq $null) { $enc = ‘UTF7‘ }
    }
    catch {}
    finally {
      if ($fs -ne $null) { $fs.Close() }
    }
  }
  end { [Text.Encoding]::$enc }
}

 http://poshcode.org/5292

 

获取文件编码方式

标签:

原文地址:http://www.cnblogs.com/IvanChen/p/4493048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!