[CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory = $true)] [string]$Destination, [string[]]$Keys = @( 'HKCU\Software', 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' ) ) $ErrorActionPreference = 'Stop' if (-not (Get-Command reg.exe -ErrorAction SilentlyContinue)) { throw 'reg.exe not found.' } $destFull = [System.IO.Path]::GetFullPath($Destination) $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' $targetRoot = Join-Path $destFull ('registry-' + $stamp) if (Test-Path -LiteralPath $targetRoot) { throw "Destination already exists: $targetRoot" } if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Export registry keys')) { return } New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null $manifest = New-Object System.Collections.Generic.List[object] $validPattern = '^(HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG|HKLM|HKCU|HKCR|HKU|HKCC)\\' foreach ($key in $Keys) { if ($key -notmatch $validPattern) { Write-Warning "Key skipped, invalid format: $key" continue } $safe = $key -replace '[\\/:*?"<>|]', '_' if ($safe.Length -gt 100) { $safe = $safe.Substring($safe.Length - 100) } $file = Join-Path $targetRoot ($safe + '.reg') if (Test-Path -LiteralPath $file) { Write-Warning "File already exists, skipped: $file" continue } & reg.exe export $key $file /y | Out-Null if ($LASTEXITCODE -ne 0) { Write-Warning "Export failed: $key" if (Test-Path -LiteralPath $file) { Remove-Item -LiteralPath $file -Force } continue } $manifest.Add([pscustomobject]@{ Key = $key File = $file Length = (Get-Item -LiteralPath $file).Length SHA256 = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash }) } $manifestPath = Join-Path $targetRoot 'manifest.csv' if ($manifest.Count -gt 0) { $manifest | Export-Csv -LiteralPath $manifestPath -NoTypeInformation -Encoding UTF8 } else { Set-Content -LiteralPath $manifestPath -Value 'Key,File,Length,SHA256' -Encoding UTF8 } Write-Host "Keys: $($manifest.Count)" Write-Host "Folder: $targetRoot"