-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgbk_to_utf8_recursive.ps1
More file actions
62 lines (52 loc) · 1.97 KB
/
gbk_to_utf8_recursive.ps1
File metadata and controls
62 lines (52 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 检测文件编码的函数
function Test-FileEncoding {
param([string]$FilePath)
$bytes = [System.IO.File]::ReadAllBytes($FilePath)
# 检查 UTF-8 BOM
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
return "UTF8-BOM"
}
# 检查是否为有效的UTF-8(无BOM)
try {
$utf8 = [System.Text.Encoding]::UTF8
$decoded = $utf8.GetString($bytes)
# 尝试重新编码,如果结果一致则可能是UTF-8
$reencoded = $utf8.GetBytes($decoded)
if ([System.Linq.Enumerable]::SequenceEqual($bytes, $reencoded)) {
return "UTF8"
}
}
catch {
# UTF-8 解码失败
}
# 默认假设是 GBK/ANSI
return "GBK"
}
# 查找所有 .cpp 文件(包括子目录)
Get-ChildItem -Path . -Filter "*.cpp" -Recurse | ForEach-Object {
$file = $_.FullName
$tempFile = "$file.utf8"
# 检测文件编码
$encoding = Test-FileEncoding -FilePath $file
if ($encoding -eq "UTF8" -or $encoding -eq "UTF8-BOM") {
Write-Host "跳过(已是UTF-8): $file" -ForegroundColor Cyan
return
}
try {
# 读取 GBK 编码文件并转换为 UTF-8 (明确指定GBK编码)
$gbkEncoding = [System.Text.Encoding]::GetEncoding(936) # CP936 = GBK
$content = [System.IO.File]::ReadAllText($file, $gbkEncoding)
[System.IO.File]::WriteAllText($tempFile, $content, [System.Text.Encoding]::UTF8)
# 替换原文件
Move-Item -Path $tempFile -Destination $file -Force
Write-Host "转换成功: $file" -ForegroundColor Green
}
catch {
# 如果转换失败,删除临时文件
if (Test-Path $tempFile) {
Remove-Item $tempFile -Force
}
Write-Host "转换失败: $file - $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host "所有 .cpp 文件处理完成!" -ForegroundColor Yellow