refactor: Improve MachineGuid backup and error handling robustness

- Added fallback backup location when default backup directory is unavailable
- Enhanced GUID parsing with additional null checks
- Improved backup file recovery error handling
- Added warning message for scenarios without backup file
- Refined error recovery mechanism with more comprehensive checks
This commit is contained in:
煎饼果子卷鲨鱼辣椒 2025-02-12 11:40:09 +08:00
parent 30af54da9c
commit dc8807f3dc

View File

@ -210,7 +210,7 @@ function Update-MachineGuid {
exit 1 exit 1
} }
# 精确解析GUID # 精确解析GUID(增加空值检查)
if ($regResult -match "MachineGuid\s+REG_SZ\s+([0-9a-fA-F-]{36})") { if ($regResult -match "MachineGuid\s+REG_SZ\s+([0-9a-fA-F-]{36})") {
$originalGuid = $matches[1].ToLower() $originalGuid = $matches[1].ToLower()
Write-Host "$GREEN[信息]$NC 当前注册表值:" Write-Host "$GREEN[信息]$NC 当前注册表值:"
@ -226,8 +226,12 @@ function Update-MachineGuid {
$newGuid = [System.Guid]::NewGuid().ToString() $newGuid = [System.Guid]::NewGuid().ToString()
$registryPath = "HKLM:\SOFTWARE\Microsoft\Cryptography" $registryPath = "HKLM:\SOFTWARE\Microsoft\Cryptography"
# 创建备份文件 # 创建备份文件(增加路径验证)
$backupFile = "$BACKUP_DIR\MachineGuid_$(Get-Date -Format 'yyyyMMdd_HHmmss').reg" $backupFile = if (Test-Path $BACKUP_DIR) {
"$BACKUP_DIR\MachineGuid_$(Get-Date -Format 'yyyyMMdd_HHmmss').reg"
} else {
"$env:TEMP\MachineGuid_$(Get-Date -Format 'yyyyMMdd_HHmmss').reg"
}
reg export "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" $backupFile | Out-Null reg export "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" $backupFile | Out-Null
Write-Host "$GREEN[信息]$NC 注册表项已备份到:$backupFile" Write-Host "$GREEN[信息]$NC 注册表项已备份到:$backupFile"
@ -246,11 +250,13 @@ function Update-MachineGuid {
} }
catch { catch {
Write-Host "$RED[错误]$NC 注册表操作失败:$_" Write-Host "$RED[错误]$NC 注册表操作失败:$_"
# 自动恢复备份 # 自动恢复备份(增加空值检查)
if (Test-Path $backupFile) { if ($backupFile -and (Test-Path $backupFile)) {
Write-Host "$YELLOW[恢复]$NC 正在从备份恢复..." Write-Host "$YELLOW[恢复]$NC 正在从备份恢复..."
reg import $backupFile | Out-Null reg import $backupFile | Out-Null
Write-Host "$GREEN[恢复成功]$NC 已还原原始注册表值" Write-Host "$GREEN[恢复成功]$NC 已还原原始注册表值"
} else {
Write-Host "$YELLOW[警告]$NC 未找到备份文件,无法自动恢复"
} }
exit 1 exit 1
} }