Enhance error handling and access restriction reporting in registry operations

This commit is contained in:
Jeffrey
2026-05-17 20:05:20 +02:00
parent 4f17727a3b
commit 54830cc928

View File

@@ -74,6 +74,9 @@ function Remove-RegistrySubKeyTreeIfExists {
try {
$RootKey.DeleteSubKeyTree($SubKeyPath, $false)
}
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
throw
}
catch {
# Best-effort cleanup only; missing keys are fine.
}
@@ -117,7 +120,10 @@ function Invoke-RegistryOperationsFromRegFile {
[string]$RegFilePath
)
$accessDeniedFailures = New-Object 'System.Collections.Generic.List[object]'
foreach ($operation in @(Get-RegFileOperations -regFilePath $RegFilePath)) {
try {
$keyInfo = Get-RegistryKeyForOperation -RegistryPath $operation.KeyPath -CreateIfMissing:($operation.OperationType -eq 'SetValue')
switch ($operation.OperationType) {
@@ -162,6 +168,36 @@ function Invoke-RegistryOperationsFromRegFile {
}
}
}
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
$valueDisplay = if ($operation.OperationType -eq 'SetValue' -or $operation.OperationType -eq 'DeleteValue') {
if ([string]::IsNullOrEmpty([string]$operation.ValueName)) { '(Default)' } else { [string]$operation.ValueName }
}
else {
''
}
$failure = [PSCustomObject]@{
OperationType = [string]$operation.OperationType
KeyPath = [string]$operation.KeyPath
ValueName = $valueDisplay
Error = $_.Exception.Message
}
$accessDeniedFailures.Add($failure)
if ([string]::IsNullOrEmpty($valueDisplay)) {
Write-Warning ("Skipping operation '{0}' on key '{1}' due to access restrictions: {2}" -f $failure.OperationType, $failure.KeyPath, $failure.Error)
}
else {
Write-Warning ("Skipping operation '{0}' on key '{1}' value '{2}' due to access restrictions: {3}" -f $failure.OperationType, $failure.KeyPath, $failure.ValueName, $failure.Error)
}
continue
}
}
if ($accessDeniedFailures.Count -gt 0) {
Write-Warning ("Registry fallback import completed with $($accessDeniedFailures.Count) access-restricted operation(s) skipped in '$RegFilePath'.")
}
}
function Invoke-RegistryImportViaPowerShell {