| name | registry-safe-edit |
| description | Safe Windows registry read/write with automatic backup and rollback support. Always exports before modifying. Use for application configuration, system tweaks, and environment settings. |
| version | 1.0.0 |
Registry Safe Edit Skill
核心原則
任何修改前必須先備份。 每次操作自動匯出目標機碼。
安全讀取
# 讀取登錄值(安全)
function Get-RegistryValue {
param(
[string]$Key,
[string]$Name
)
try {
$value = Get-ItemPropertyValue -Path $Key -Name $Name -ErrorAction Stop
return $value
}
catch [System.Management.Automation.ItemNotFoundException] {
Write-Warning "機碼不存在:$Key"
return $null
}
}
# 使用
$proxy = Get-RegistryValue "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" "ProxyServer"
安全修改(含自動備份)
function Set-RegistryValueSafe {
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$Key,
[string]$Name,
$Value,
[Microsoft.Win32.RegistryValueKind]$Type = [Microsoft.Win32.RegistryValueKind]::String
)
# 1. 先備份
$backupDir = "$env:LOCALAPPDATA\windows-agent\registry-backups"
New-Item -ItemType Directory -Path $backupDir -Force | Out-Null
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupFile = "$backupDir\backup_$timestamp.reg"
$regPath = $Key -replace "^HKCU:", "HKEY_CURRENT_USER" `
-replace "^HKLM:", "HKEY_LOCAL_MACHINE"
reg export $regPath $backupFile /y | Out-Null
Write-Host "備份至:$backupFile"
# 2. 確認後修改
if ($PSCmdlet.ShouldProcess("$Key\$Name", "Set to '$Value'")) {
if (-not (Test-Path $Key)) {
New-Item -Path $Key -Force | Out-Null
}
Set-ItemProperty -Path $Key -Name $Name -Value $Value -Type $Type -ErrorAction Stop
Write-Host "已設定 $Name = $Value"
}
}
回滾
# 列出最近備份
Get-ChildItem "$env:LOCALAPPDATA\windows-agent\registry-backups" |
Sort-Object LastWriteTime -Descending |
Select-Object -First 10 Name, LastWriteTime
# 回滾指定備份
$backupFile = "$env:LOCALAPPDATA\windows-agent\registry-backups\backup_20260425_103000.reg"
reg import $backupFile
參考資料
references/rollback.md — 回滾策略與步驟