终极修复版 PowerShell 脚本 (Convert-Encoding.ps1)
下面的是代码开头
param(
[Parameter(Mandatory=$true)]
[string]$targetPath
)
function Convert-File {
param($file)
try {
# 使用高级编码检测方法
$stream = [System.IO.File]::OpenRead($file.FullName)
$reader = New-Object System.IO.StreamReader($stream, $true) # 自动检测编码
$content = $reader.ReadToEnd()
$detectedEncoding = $reader.CurrentEncoding
$reader.Close()
$stream.Close()
# 跳过已经是UTF-16 LE的文件
if ($detectedEncoding.BodyName -eq 'utf-16') {
Write-Host "[⚠️跳过] $($file.FullName) (已是UTF-16编码)" -ForegroundColor Cyan
return
}
# 二进制模式验证原始编码
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
$validationContent = $detectedEncoding.GetString($bytes)
if ($validationContent -ne $content) {
throw "编码验证失败:检测到编码不一致"
}
# 写入UTF-16 LE带BOM
[System.IO.File]::WriteAllText(
$file.FullName,
$content,
[System.Text.Encoding]::Unicode
)
Write-Host "[✅成功] $($file.FullName) (原编码: $($detectedEncoding.EncodingName))" -ForegroundColor Green
} catch {
Write-Host "[❌失败] $($file.FullName)" -ForegroundColor Red
Write-Host "错误详情: $($_.Exception.Message)" -ForegroundColor Yellow
# 保留原始文件备份
$backupPath = $file.FullName + ".bak"
if (-not (Test-Path $backupPath)) {
Copy-Item $file.FullName $backupPath
}
}
}
# 主程序
if (Test-Path -LiteralPath $targetPath -PathType Container) {
Get-ChildItem -LiteralPath $targetPath -Filter *.txt -Recurse -File | ForEach-Object {
Convert-File $_
}
} else {
Convert-File (Get-Item -LiteralPath $targetPath -Force)
}
代码在这就结束了
配套批处理文件更新 (拖放转换.bat)
下面的是代码开头
@璐村惂鐢ㄦ埛_000076K馃惥 off
chcp 65001 > nul
setlocal disabledelayedexpansion
if "%~1"=="" (
echo 请将文件或文件夹拖放到此批处理文件图标上
pause
exit /b
)
set "psPath=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
set "scriptPath=%~dp0Convert-Encoding.ps1"
echo 正在处理:%~1
echo 注意:转换失败的文件会自动生成.bak备份
"%psPath%" -ExecutionPolicy Bypass -NoProfile -Command ". \"%scriptPath:\=\\%\" -targetPath \"%~f1\""
pause
代码在这就结束了
使用说明
保存文件
将两个脚本保存到同一文件夹
确保文件名精确匹配:
拖放转换.bat
Convert-Encoding.ps1
执行转换
直接拖放 文件或文件夹 到批处理文件图标上
根据UAC提示授予管理员权限