txt其他所有格式批量转成utf-8
Uncategorized使用 PowerShell 脚本(无需安装软件,推荐)
这是 Windows 自带的工具,处理速度快且无需下载第三方程序。
-
在包含
.txt文件的文件夹中,按住 Shift 键并右键点击空白处,选择“在此处打开 PowerShell 窗口”。 -
输入并运行以下代码(你可以直接复制粘贴):
$files = Get-ChildItem -Filter *.txt -Recurse
foreach ($file in $files) {
$filePath = $file.FullName
# 1. 读取文件开头的原始字节(用于判断编码)
$bytes = [System.IO.File]::ReadAllBytes($filePath)
if ($bytes.Length -eq 0) { continue } # 跳过空文件
$encoding = $null
# 2. 判断是否已经是 UTF-8 (检查 BOM)
if ($bytes[0] -eq 0xef -and $bytes[1] -eq 0xbb -and $bytes[2] -eq 0xbf) {
Write-Host "已经是 UTF-8 (BOM): $filePath" -ForegroundColor Gray
continue
}
# 3. 简单的启发式判断:如果没有 BOM,尝试检测是否是不带 BOM 的 UTF-8
# 这里通过尝试解码来判断
try {
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false, $true)
$junk = $Utf8NoBom.GetString($bytes)
Write-Host "已经是 UTF-8 (No BOM): $filePath" -ForegroundColor Gray
continue
}
catch {
# 如果报错,说明不是正确的 UTF-8 编码,需要转换
Write-Host "检测到非 UTF-8 编码,正在转换: $filePath" -ForegroundColor Yellow
}
# 4. 执行转换 (从 ANSI/GB18030 转为 UTF-8)
try {
# GB18030 兼容 GBK 和 GB2312,是中文环境最稳妥的选择
$srcEncoding = [System.Text.Encoding]::GetEncoding("GB18030")
$content = [System.IO.File]::ReadAllText($filePath, $srcEncoding)
# 写入为带 BOM 的 UTF-8,确保 Windows 记事本和 WordPress 导入都能识别
[System.IO.File]::WriteAllText($filePath, $content, [System.Text.Encoding]::UTF8)
Write-Host "--- 成功转换: $filePath" -ForegroundColor Green
}
catch {
Write-Host "!!! 转换失败: $filePath (原因: $($_.Exception.Message))" -ForegroundColor Red
}
}
Write-Host "`n所有任务已完成!" -ForegroundColor Cyan
pause
这个脚本会自动遍历当前文件夹及其所有子文件夹(-Recurse),并将所有 .txt 文件转换为 UTF-8 编码。