【解决方案】
以下代码以ANSI编码保存为 Run.bat 放在 C:\Test\U2A 文件夹下:- @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
- for /f "delims=" %%b in ('powershell -f CheckCode.ps1 "%%a"') do (
- if "%%b" == "UTF-8BOM" (
- powershell "[IO.File]::WriteAllLines('%FolderStageU%\%%a',(Get-Content '%%a' -Raw))"
- iconv.exe -f UTF-8 -t GB2312 "%FolderStageU%\%%a" > "%FolderOutA%\%%a" 2>nul
- ) else (
- iconv.exe -f UTF-8 -t GB2312 "%%a" > "%FolderOutA%\%%a" 2>nul
- if errorlevel 1 (
- iconv.exe -t GB2312 "%%a" > "%FolderOutA%\%%a"
- )
- )
- )
- )
复制代码 以下代码以ANSI编码保存为 CheckCode.ps1 放在 C:\Test\U2A 文件夹下:- function Get-FileEncoding {
- [CmdletBinding()]
- param (
- [Parameter(Mandatory = $true)]
- [ValidateScript({ Test-Path $_ })]
- [string]$Path
- )
- $byte = Get-Content -Encoding Byte -ReadCount 2 -TotalCount 2 -Path $Path
- if ($byte[0] -eq 0xEF -and $byte[1] -eq 0xBB) {
- return 'UTF-8BOM'
- } elseif ([System.Text.Encoding]::UTF8.GetString($byte) -match '[^\x00-\x7F]') {
- return 'UTF-8'
- } else {
- return 'ANSI'
- }
- }
- $StrEncode = Get-FileEncoding -Path $Args[0]
- Write-Host "$StrEncode"
复制代码 下载命令行工具 iconv.exe 放在 C:\Test\U2A 文件夹下:
http://bcn.bathome.net/s/tool/index.html?key=iconv
执行 Run.bat 脚本即可。 |