回复 4# Batcher
抄了下你的代码和内容、、、
以下代码以ANSI编码保存为 ChangeCoding.ps1 放在 C:\Test\U2A 文件夹下:- $byte =[io.file]::ReadAllBytes($Args[0])
-
- $d=[Text.DecoderReplacementFallback]::new('?')
- $e=[Text.EncoderReplacementFallback]::new('?')
- $cgbk=[text.encoding]::GetEncoding(936,$e,$d)
- $cutf8=[text.encoding]::GetEncoding(65001,$e,$d)
-
- $StrEncode='ANSI'
-
- if($byte.length -le 512){$l=$byte.length} else{$l=512}
- echo "test $l bytes"
-
- if ($byte[0] -eq 0xEF -and $byte[1] -eq 0xBB){
- $StrEncode='UTF-8BOM'
- } else{
- $b=$cgbk.GetBytes($cgbk.GetString($byte,0,$l))
- if($l -eq 512){$l-=16}
- for($i=0;$i -lt $l;$i++){
- if($b[$i] -ne $byte[$i] ){$StrEncode='UTF-8';break}
- }
- }
-
- echo "maybe $StrEncode"
-
- if($StrEncode -eq 'UTF-8BOM'){
- echo "convert $StrEncode to ANSI"
- [io.file]::WriteAllText($Args[1],$cutf8.GetString($byte,3,$byte.length-3),$cgbk)
- }
- if($StrEncode -eq 'UTF-8'){
- echo "convert $StrEncode to ANSI"
- [io.file]::WriteAllText($Args[1],$cutf8.GetString($byte,0,$byte.length),$cgbk)
- }
- if($StrEncode -eq 'ANSI'){}
- echo "`r`n"
复制代码 以下代码以ANSI编码保存为 Run.bat 放在 C:\Test\U2A 文件夹下:
执行 Run.bat 脚本即可。- @echo off
- cd /d "%~dp0"
- set "FolderStageU=TempUTF8BOM"
- set "FolderOutA=FinalANSI"
- md "%FolderStageU%" 2>nul
- md "%FolderOutA%" 2>nul
- for /f "delims=" %%a in ('dir /b /a-d *.txt') do (
- echo %%a
- powershell -ExecutionPolicy bypass -f ChangeCoding.ps1 "%%~fa" "%~dp0%FolderOutA%\%%a"
- )
- pause
复制代码
|