最近用deepseek弄了个UTF-8转UTF-16 LE的小工具
读书巴士吧
全部回复
仅看楼主
level 7
【支持老版本PowerShell,自动临时获取管理员权限执行PowerShell 脚本,检测TXT文件是否为UTF-16 LE防止重复转换变成乱码,支持复杂文件名和文件夹名【我正在用的那个软件不支持。。。文件名里带个❤️就直接卡死】,搭配PowerShell 脚本的批处理文件,把文件夹直接丢进批处理文件里就能把整个文件夹里的TXT文件全部转换成UTF-16 LE,验证确保转换前后内容语义一致防止转换后TXT文件内容缺失】
2025年01月27日 12点01分 1
level 7
终极修复版 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提示授予管理员权限
2025年01月27日 12点01分 2
度娘把空格都删了,也不知道能不能用,还是直接丢网盘好了[汗]
2025年01月27日 12点01分
https://share.weiyun.com/Mtn7FALk UTF-8转换UTF-16 LE文件夹里面的就是了
2025年01月27日 12点01分
批处理文件那开头还乱码了。。。。那里是echo off
2025年01月27日 12点01分
level 7
Win+R 输入 shell:sendto 回车
把启动转换.bat的快捷方式放进去
之后只要右键SHIFT+A括住全部文档再右键发动到启动转换.bat就可以了,这样就不用来回拖鼠标了。
7.3凌晨——发现右键发送多个文件过去只处理第一个,告诉豆包后更新了一下批文件,现在可以进行上面的操作了。
7.3早上——不知道是不是我的系统问题,突然批处理文件就失效了,连带老版本的也失效了,最后跟豆包对话了很久,弄了个最新版能用的。
工具在网盘那
2026年07月02日 22点07分 8
1