[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖
本帖最后由 went 于 2022-1-12 15:44 编辑

获取文件编码的函数
  1. #函数 获取文件编码
  2. function Get-FileCoder($file_path){
  3.     $bytes = [System.IO.File]::ReadAllBytes($file_path)
  4.     if($bytes[0] -eq 0xff -and $bytes[1] -eq 0xfe){ return 'utf-16_le' }
  5.     if($bytes[0] -eq 0xfe -and $bytes[1] -eq 0xff){ return 'utf-16_be' }
  6.     if($bytes[0] -eq 0xef -and $bytes[1] -eq 0xbb -and $bytes[2] -eq 0xbf){ return 'utf-8_bom' }
  7.     $index = 0; $bu8 = $false
  8.     while($index -lt $bytes.Count){
  9.         $one = 0
  10.         for($i = 0; $i -lt 8; $i++){
  11.             if(($bytes[$index] -band (0x80 -shr $i)) -eq 0){ break; }
  12.             ++$one
  13.         }
  14.         if($one -eq 0){
  15.             ++$index
  16.         } else {
  17.             if($one -eq 1){ return 'ansi' }
  18.             $bu8 = $true
  19.             for($i = 0; $i -lt $one-1; $i++){
  20.                 ++$index
  21.                 if(($bytes[$index] -band 0x80) -ne 0x80){ return 'ansi' }
  22.             }
  23.             ++$index
  24.         }
  25.     }
  26.     if($bu8){return 'utf-8'} else { return 'ansi'}
  27. }
复制代码

TOP

  1. $cp = Get-FileCoder -file_path 't.txt'
  2. if($cp -eq 'utf-8'){
  3.     $s = Get-Content -Encoding UTF8 -Path 't.txt'
  4. } elseif( $cp -eq 'ansi'){
  5.     $s = Get-Content -Encoding Default -Path 't.txt'
  6. }
  7. [System.IO.File]::WriteAllLines('t2.txt',$s)
复制代码
1

评分人数

    • 5i365: 非常感谢, 解决了我长期困扰的问题!技术 + 1

TOP

返回列表