You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.3 KiB
PowerShell

1 month ago
# ConvertToUTF8BOM.ps1
# 1. 获取所有待处理的 .h 和 .cpp 文件列表
$files = Get-ChildItem -Path . -Recurse -Include *.h,*.cpp -File
# 2. 记录总数,用于进度计算
$total = $files.Count
if ($total -eq 0) {
Write-Host "未找到任何 .h 或 .cpp 文件。"
exit
}
# 3. 逐个文件处理,并显示进度
$index = 0
foreach ($file in $files) {
$index++
# 为了避免 "$total:" 被当成不合法的变量,将整个表达式用 ${} 包起来
$statusText = "${index} / ${total}: $($file.FullName)"
$percent = [int](($index / $total) * 100)
Write-Progress -Activity "正在转换文件编码..." `
-Status $statusText `
-PercentComplete $percent
# 读取原文件内容(假设是 UTF-8 无 BOM
try {
$content = Get-Content -Raw -Encoding UTF8 $file.FullName
}
catch {
# 如果无法按 UTF-8 读取,就跳过,并打印一条警告
Write-Host "跳过(非 UTF-8 编码或读取失败):$($file.FullName)"
continue
}
# 以 UTF-8 带 BOM 写回
Set-Content -Path $file.FullName -Value $content -Encoding UTF8BOM
}
# 4. 完成后,清掉进度条,输出提示
Write-Progress -Activity "正在转换文件编码..." -Completed
Write-Host "转换完成,共处理 $total 个文件。"