19 Commits

Author SHA1 Message Date
Jeffrey
b0b4615718 Add verbose logging for missing registry keys in Invoke-RegistryDeleteValueOperation 2026-05-17 23:43:35 +02:00
Jeffrey
9a375fdbc4 Refactor registry operation functions 2026-05-17 23:39:41 +02:00
Jeffrey
c3a313c084 Add safety net for offline hive cleanup during registry import fallback 2026-05-17 23:25:03 +02:00
Jeffrey
dd6c65ddb0 Clean up error message 2026-05-17 23:20:00 +02:00
Jeffrey
05bd5f4c56 Refactor Invoke-RegistryOperationsFromRegFile to optimize operation handling and improve access restriction reporting 2026-05-17 23:16:32 +02:00
Jeffrey
c945789d58 Add support for Hex7 type in Convert-RegOperationToValueKind function 2026-05-17 23:13:08 +02:00
Jeffrey
ff90caa338 Refactor registry import functions to improve error handling and streamline hive management 2026-05-17 21:39:35 +02:00
Jeffrey
3363962d64 Add back support for REG_MULTI_SZ in Convert-RegValueData 2026-05-17 20:13:48 +02:00
Jeffrey
cf78eeabce Refactor registry key handling to improve key opening logic and streamline deletion operations 2026-05-17 20:06:14 +02:00
Jeffrey
54830cc928 Enhance error handling and access restriction reporting in registry operations 2026-05-17 20:05:20 +02:00
Jeffrey
4f17727a3b Enhance registry value handling for Hex and Binary types in Convert-RegOperationToValueKind function 2026-05-17 20:00:40 +02:00
Jeffrey
1776e8dae7 Remove REG_MULTI_SZ (not necessary right now) 2026-05-17 19:56:36 +02:00
Jeffrey
bef463df4d Improve registry operation handling 2026-05-17 18:45:51 +02:00
Jeffrey
c7cf793c9e Remove unblocking logic as it doesnt work 2026-05-17 18:39:19 +02:00
Jeffrey
56997dd023 Improve fallback handling and error reporting 2026-05-17 18:27:29 +02:00
Jeffrey
959f79bc35 Add Registry write fall-back in case applying registry file fails 2026-05-17 17:24:08 +02:00
Jeffrey
51aa288dfd Bump version 2026-05-12 00:01:57 +02:00
Jeffrey
24a6f1bcf8 Fix capture and restore of signed dword/qword registry values
Co-authored-by: Copilot <copilot@github.com>
2026-05-11 19:14:08 +02:00
Jeffrey
8ac664e45f Add restart instructions to registry restore success message 2026-05-10 23:26:22 +02:00
7 changed files with 417 additions and 27 deletions

View File

@@ -226,12 +226,19 @@ function Convert-RegistryValueToSnapshot {
$valueKind = $RegistryKey.GetValueKind($ValueName)
$value = $RegistryKey.GetValue($ValueName, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
$normalizedValue = switch ($valueKind) {
([Microsoft.Win32.RegistryValueKind]::Binary) { @($value | ForEach-Object { [int]$_ }) }
([Microsoft.Win32.RegistryValueKind]::MultiString) { @($value) }
([Microsoft.Win32.RegistryValueKind]::DWord) { [uint32]$value }
([Microsoft.Win32.RegistryValueKind]::QWord) { [uint64]$value }
default { if ($null -ne $value) { [string]$value } else { $null } }
try {
$normalizedValue = switch ($valueKind) {
([Microsoft.Win32.RegistryValueKind]::Binary) { @($value | ForEach-Object { [int]$_ }) }
([Microsoft.Win32.RegistryValueKind]::MultiString) { @($value) }
([Microsoft.Win32.RegistryValueKind]::DWord) { [BitConverter]::ToUInt32([BitConverter]::GetBytes([int32]$value), 0) }
([Microsoft.Win32.RegistryValueKind]::QWord) { [BitConverter]::ToUInt64([BitConverter]::GetBytes([int64]$value), 0) }
default { if ($null -ne $value) { [string]$value } else { $null } }
}
}
catch {
$valueType = if ($null -ne $value) { $value.GetType().FullName } else { '<null>' }
$valueForLog = if ($null -eq $value) { '<null>' } elseif ($value -is [array]) { ($value -join ',') } else { [string]$value }
throw "Failed to normalize registry value for backup. Key='$($RegistryKey.Name)' Name='$ValueName' Kind='$valueKind' RawType='$valueType' RawValue='$valueForLog'. InnerError: $($_.Exception.Message)"
}
return @{

View File

@@ -170,7 +170,12 @@ function ExecuteAllChanges {
}
Write-Host "> Creating registry backup..."
New-RegistrySettingsBackup -ActionableKeys $actionableKeys | Out-Null
try {
New-RegistrySettingsBackup -ActionableKeys $actionableKeys | Out-Null
}
catch {
throw "Registry backup failed before applying changes. $($_.Exception.Message)"
}
}
# Create restore point if requested (CLI only - GUI handles this separately)

View File

@@ -8,6 +8,7 @@ function ImportRegistryFile {
Write-Host $message
$usesOfflineHive = $script:Params.ContainsKey("Sysprep") -or $script:Params.ContainsKey("User")
$hiveDatPath = $null
$regFilePath = if ($usesOfflineHive) {
"$script:RegfilesPath\Sysprep\$path"
}
@@ -22,9 +23,6 @@ function ImportRegistryFile {
throw $errorMessage
}
# Reset exit code before running reg.exe for reliable success detection
$global:LASTEXITCODE = 0
if ($usesOfflineHive) {
# Sysprep targets Default user, User targets the specified user
$hiveDatPath = if ($script:Params.ContainsKey("Sysprep")) {
@@ -39,7 +37,10 @@ function ImportRegistryFile {
Output = @()
ExitCode = 0
Error = $null
FailureStage = $null
HiveLeftLoaded = $false
}
$hiveLoaded = $false
try {
$global:LASTEXITCODE = 0
@@ -47,9 +48,12 @@ function ImportRegistryFile {
$loadExitCode = $LASTEXITCODE
if ($loadExitCode -ne 0) {
$result.FailureStage = 'load'
throw "Failed to load user hive at '$hivePath' (exit code: $loadExitCode)"
}
$hiveLoaded = $true
$output = reg import $targetRegFilePath 2>&1
$importExitCode = $LASTEXITCODE
@@ -59,20 +63,32 @@ function ImportRegistryFile {
$result.ExitCode = $importExitCode
if ($importExitCode -ne 0) {
$result.FailureStage = 'import'
throw "Registry import failed with exit code $importExitCode for '$targetRegFilePath'"
}
}
catch {
if (-not $result.FailureStage) {
$result.FailureStage = 'unknown'
}
$result.Error = $_.Exception.Message
$result.ExitCode = if ($LASTEXITCODE -ne 0) { $LASTEXITCODE } else { 1 }
}
finally {
$global:LASTEXITCODE = 0
reg unload "HKU\Default" | Out-Null
$unloadExitCode = $LASTEXITCODE
if ($unloadExitCode -ne 0 -and -not $result.Error) {
$result.Error = "Failed to unload registry hive HKU\Default (exit code: $unloadExitCode)"
$result.ExitCode = $unloadExitCode
# When import failed the hive stays mounted so the PowerShell
# fallback can reuse it immediately without a load/unload race.
if ($hiveLoaded -and $result.FailureStage -eq 'import') {
$result.HiveLeftLoaded = $true
}
elseif ($hiveLoaded) {
$global:LASTEXITCODE = 0
reg unload "HKU\Default" | Out-Null
$unloadExitCode = $LASTEXITCODE
if ($unloadExitCode -ne 0 -and -not $result.Error) {
$result.FailureStage = 'unload'
$result.Error = "Failed to unload registry hive HKU\Default (exit code: $unloadExitCode)"
$result.ExitCode = $unloadExitCode
}
}
}
@@ -107,10 +123,45 @@ function ImportRegistryFile {
if (-not $hasSuccess) {
$details = if ($regResult.Error) { $regResult.Error } else { "Exit code: $($regResult.ExitCode)" }
$errorMessage = "Failed importing registry file '$path'. $details"
Write-Host $errorMessage -ForegroundColor Red
Write-Host ""
throw $errorMessage
# Fallback only helps when the import step failed. If load/unload failed,
# retrying fallback will hit the same hive-state problem and adds noisy errors.
if ($usesOfflineHive -and ($regResult.FailureStage -eq 'load' -or $regResult.FailureStage -eq 'unload')) {
$errorMessage = "Failed importing registry file '$path'. Offline hive $($regResult.FailureStage) failed: $details"
Write-Host $errorMessage -ForegroundColor Red
Write-Host ""
throw $errorMessage
}
Write-Warning "reg import failed for '$path'. Falling back to PowerShell registry writer. Details: $details"
try {
Invoke-RegistryImportViaPowerShell -RegFilePath $regFilePath -UseOfflineHive:$usesOfflineHive -OfflineHiveDatPath $hiveDatPath -HiveAlreadyLoaded:([bool]$regResult.HiveLeftLoaded)
Write-Host "Fallback import succeeded for '$path'." -ForegroundColor Yellow
Write-Host ""
return
}
catch {
if ($usesOfflineHive -and [bool]$regResult.HiveLeftLoaded) {
# Safety net: if fallback failed before unloading the preloaded hive,
# attempt cleanup here to avoid leaving HKU\Default mounted.
$global:LASTEXITCODE = 0
reg query "HKU\Default" | Out-Null
if ($LASTEXITCODE -eq 0) {
$global:LASTEXITCODE = 0
reg unload "HKU\Default" | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Warning "Fallback cleanup failed: unable to unload HKU\Default after fallback error (exit code: $LASTEXITCODE)."
}
}
}
$errorMessage = "Failed importing registry file '$path'. reg import error: $details. PowerShell fallback error: $($_.Exception.Message)"
Write-Host $errorMessage -ForegroundColor Red
Write-Host ""
throw $errorMessage
}
}
Write-Host ""

View File

@@ -157,8 +157,14 @@ function Convert-RegistryValueDataFromBackup {
)
switch ($Kind) {
([Microsoft.Win32.RegistryValueKind]::DWord) { return [uint32]$Data }
([Microsoft.Win32.RegistryValueKind]::QWord) { return [uint64]$Data }
([Microsoft.Win32.RegistryValueKind]::DWord) {
$unsigned = [uint32]$Data
return [BitConverter]::ToInt32([BitConverter]::GetBytes($unsigned), 0)
}
([Microsoft.Win32.RegistryValueKind]::QWord) {
$unsigned = [uint64]$Data
return [BitConverter]::ToInt64([BitConverter]::GetBytes($unsigned), 0)
}
([Microsoft.Win32.RegistryValueKind]::MultiString) { return @($Data | ForEach-Object { [string]$_ }) }
([Microsoft.Win32.RegistryValueKind]::Binary) {
$bytes = Convert-BackupDataToByteArray -Data $Data

View File

@@ -24,7 +24,7 @@ function Show-RestoreBackupWindow {
Write-Host "User confirmed registry restore for $($backup.Target)."
Restore-RegistryBackupState -Backup $backup
$successMessage = 'Registry backup restored successfully.'
$successMessage = 'Registry backup restored successfully. Please restart your computer for all changes to take effect.'
}
elseif ($dialogResult.Result -eq 'RestoreStartMenu') {
$scope = $dialogResult.StartMenuScope

View File

@@ -0,0 +1,320 @@
function Get-NormalizedRegistryValueName {
param(
[AllowNull()]
$ValueName
)
if ([string]::IsNullOrEmpty([string]$ValueName)) {
return ''
}
return [string]$ValueName
}
function Convert-RegOperationToValueKind {
param(
[Parameter(Mandatory)]
$Operation
)
$valueName = if ([string]::IsNullOrEmpty([string]$Operation.ValueName)) { '' } else { [string]$Operation.ValueName }
$valueType = [string]$Operation.ValueType
$operationKeyPath = [string]$Operation.KeyPath
switch ($valueType) {
'DWord' {
$unsigned = [uint32]$Operation.ValueData
$value = [BitConverter]::ToInt32([BitConverter]::GetBytes($unsigned), 0)
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::DWord; Value = $value }
}
'QWord' {
$unsigned = [uint64]$Operation.ValueData
$value = [BitConverter]::ToInt64([BitConverter]::GetBytes($unsigned), 0)
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::QWord; Value = $value }
}
'String' {
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::String; Value = [string]$Operation.ValueData }
}
'Binary' {
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::Binary; Value = [byte[]]$Operation.ValueData }
}
'Hex0' {
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::None; Value = [byte[]]$Operation.ValueData }
}
'Hex1' {
$stringValue = ([System.Text.Encoding]::Unicode.GetString([byte[]]$Operation.ValueData)).TrimEnd([char]0)
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::String; Value = $stringValue }
}
'Hex2' {
$expandStringValue = if ($Operation.ValueData -is [byte[]]) {
([System.Text.Encoding]::Unicode.GetString([byte[]]$Operation.ValueData)).TrimEnd([char]0)
}
else {
[string]$Operation.ValueData
}
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString; Value = $expandStringValue }
}
'Hex7' {
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::MultiString; Value = [string[]]$Operation.ValueData }
}
{ $valueType -in @('Hex3', 'Hex4', 'Hex5') } {
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::Binary; Value = [byte[]]$Operation.ValueData }
}
'HexB' {
$qwordBytes = [byte[]]$Operation.ValueData
if ($qwordBytes.Count -gt 8) {
throw "Unsupported hex value type '$valueType' with invalid byte count '$($qwordBytes.Count)' while applying reg operation for '$operationKeyPath'."
}
if ($qwordBytes.Count -lt 8) {
$paddedBytes = New-Object byte[] 8
[Array]::Copy($qwordBytes, $paddedBytes, $qwordBytes.Count)
$qwordBytes = $paddedBytes
}
$unsigned = [BitConverter]::ToUInt64($qwordBytes, 0)
$signed = [BitConverter]::ToInt64([BitConverter]::GetBytes($unsigned), 0)
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::QWord; Value = $signed }
}
default {
if ($valueType -like 'Hex*') {
throw "Unsupported hex value type '$valueType' while applying reg operation for '$operationKeyPath'."
}
throw "Unsupported value type '$valueType' while applying reg operation for '$operationKeyPath'"
}
}
}
function Remove-RegistrySubKeyTreeIfExists {
param(
[Parameter(Mandatory)]
[Microsoft.Win32.RegistryKey]$RootKey,
[Parameter(Mandatory)]
[string]$SubKeyPath
)
try {
$RootKey.DeleteSubKeyTree($SubKeyPath, $false)
}
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
throw
}
catch {
# Best-effort cleanup only; missing keys are fine.
}
}
function Get-RegistryKeyForOperation {
param(
[Parameter(Mandatory)]
[string]$RegistryPath,
[switch]$CreateIfMissing,
[bool]$OpenKey = $true
)
$parts = Split-RegistryPath -path $RegistryPath
if (-not $parts) {
throw "Unsupported registry path: $RegistryPath"
}
$rootKey = Get-RegistryRootKey -hiveName $parts.Hive
if (-not $rootKey) {
throw "Unsupported registry hive '$($parts.Hive)' in path '$RegistryPath'"
}
$subKeyPath = $parts.SubKey
if ([string]::IsNullOrWhiteSpace($subKeyPath)) {
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $null; Key = $rootKey }
}
if (-not $OpenKey) {
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $subKeyPath; Key = $null }
}
$key = if ($CreateIfMissing) {
$rootKey.CreateSubKey($subKeyPath)
}
else {
$rootKey.OpenSubKey($subKeyPath, $true)
}
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $subKeyPath; Key = $key }
}
function Invoke-RegistryDeleteValueOperation {
param(
[Parameter(Mandatory)]
$Operation,
[Parameter(Mandatory)]
$KeyInfo
)
if ($null -eq $KeyInfo.Key) {
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
$displayValueName = if ([string]::IsNullOrEmpty($valueName)) { '(Default)' } else { $valueName }
Write-Verbose "Unable to find or open key '$($Operation.KeyPath)' and value '$displayValueName'"
return
}
try {
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
$KeyInfo.Key.DeleteValue($valueName, $false)
}
finally {
$KeyInfo.Key.Close()
}
}
function Invoke-RegistrySetValueOperation {
param(
[Parameter(Mandatory)]
$Operation,
[Parameter(Mandatory)]
$KeyInfo
)
if ($null -eq $KeyInfo.Key) {
throw [System.UnauthorizedAccessException]::new("Unable to open or create registry key '$($Operation.KeyPath)'")
}
try {
$setArgs = Convert-RegOperationToValueKind -Operation $Operation
$KeyInfo.Key.SetValue($setArgs.Name, $setArgs.Value, $setArgs.Kind)
}
finally {
$KeyInfo.Key.Close()
}
}
function Write-RegistryOperationAccessDeniedWarning {
param(
[Parameter(Mandatory)]
$Operation,
[Parameter(Mandatory)]
[string]$ExceptionMessage
)
$keyPath = [string]$Operation.KeyPath
$operationType = [string]$Operation.OperationType
if ($operationType -eq 'SetValue' -or $operationType -eq 'DeleteValue') {
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
$displayValueName = if ([string]::IsNullOrEmpty($valueName)) { '(Default)' } else { $valueName }
Write-Warning "Skipping operation '$operationType' on key '$keyPath' value '$displayValueName' due to access restrictions: $ExceptionMessage"
return
}
Write-Warning "Skipping operation '$operationType' on key '$keyPath' due to access restrictions: $ExceptionMessage"
}
function Invoke-RegistryOperation {
param(
[Parameter(Mandatory)]
$Operation,
[Parameter(Mandatory)]
[string]$RegFilePath
)
$operationType = [string]$Operation.OperationType
$isSetValueOperation = $operationType -eq 'SetValue'
$isDeleteKeyOperation = $operationType -eq 'DeleteKey'
$keyInfo = Get-RegistryKeyForOperation -RegistryPath $Operation.KeyPath -CreateIfMissing:$isSetValueOperation -OpenKey:(-not $isDeleteKeyOperation)
switch ($operationType) {
'DeleteKey' {
if ($null -ne $keyInfo.SubKeyPath) {
Remove-RegistrySubKeyTreeIfExists -RootKey $keyInfo.RootKey -SubKeyPath $keyInfo.SubKeyPath
}
}
'DeleteValue' {
Invoke-RegistryDeleteValueOperation -Operation $Operation -KeyInfo $keyInfo
}
'SetValue' {
Invoke-RegistrySetValueOperation -Operation $Operation -KeyInfo $keyInfo
}
default {
throw "Unsupported reg operation type '$($Operation.OperationType)' in '$RegFilePath'"
}
}
}
function Invoke-RegistryOperationsFromRegFile {
param(
[Parameter(Mandatory)]
[string]$RegFilePath
)
$accessDeniedCount = 0
$operations = @(Get-RegFileOperations -regFilePath $RegFilePath)
$totalOperations = $operations.Count
foreach ($operation in $operations) {
try {
Invoke-RegistryOperation -Operation $operation -RegFilePath $RegFilePath
}
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
$accessDeniedCount++
Write-RegistryOperationAccessDeniedWarning -Operation $operation -ExceptionMessage $_.Exception.Message
}
}
if ($totalOperations -gt 0 -and $accessDeniedCount -eq $totalOperations) {
throw "Registry fallback import could not apply any operations in '$RegFilePath' because all $accessDeniedCount operation(s) were blocked by access restrictions."
}
if ($accessDeniedCount -gt 0) {
Write-Warning "Registry fallback import completed with $accessDeniedCount access-restricted operation(s) skipped in '$RegFilePath'."
}
}
function Invoke-RegistryImportViaPowerShell {
param(
[Parameter(Mandatory)]
[string]$RegFilePath,
[switch]$UseOfflineHive,
[string]$OfflineHiveDatPath,
[switch]$HiveAlreadyLoaded
)
$applyScript = {
param($targetRegFilePath)
Invoke-RegistryOperationsFromRegFile -RegFilePath $targetRegFilePath
}
$hiveAlreadyLoaded = $HiveAlreadyLoaded.IsPresent
if ($UseOfflineHive) {
if ((Get-Command -Name Invoke-WithLoadedBackupHive -ErrorAction SilentlyContinue) -and -not $hiveAlreadyLoaded) {
return Invoke-WithLoadedBackupHive -ScriptBlock $applyScript -ArgumentObject $RegFilePath
}
if ([string]::IsNullOrWhiteSpace($OfflineHiveDatPath)) {
throw "Offline hive path was not provided for fallback import of '$RegFilePath'"
}
if (-not $hiveAlreadyLoaded) {
$global:LASTEXITCODE = 0
reg load "HKU\Default" $OfflineHiveDatPath | Out-Null
$loadExitCode = $LASTEXITCODE
if ($loadExitCode -ne 0) {
throw "Failed to load user hive at '$OfflineHiveDatPath' for fallback import (exit code: $loadExitCode)"
}
}
try {
return & $applyScript $RegFilePath
}
finally {
$global:LASTEXITCODE = 0
reg unload "HKU\Default" | Out-Null
$unloadExitCode = $LASTEXITCODE
if ($unloadExitCode -ne 0) {
Write-Warning "Fallback import completed, but unloading HKU\Default failed (exit code: $unloadExitCode)."
}
}
}
return & $applyScript $RegFilePath
}

View File

@@ -141,7 +141,7 @@ if (-not $isAdmin) {
}
# Define script-level variables & paths
$script:Version = "2026.05.10"
$script:Version = "2026.05.11"
$configPath = Join-Path $PSScriptRoot 'Config'
$logsPath = Join-Path $PSScriptRoot 'Logs'
$schemasPath = Join-Path $PSScriptRoot 'Schemas'
@@ -349,6 +349,7 @@ if (-not $script:WingetInstalled -and -not $Silent) {
. "$PSScriptRoot/Scripts/Helpers/GetUserDirectory.ps1"
. "$PSScriptRoot/Scripts/Helpers/GetUserName.ps1"
. "$PSScriptRoot/Scripts/Helpers/RegistryPathHelpers.ps1"
. "$PSScriptRoot/Scripts/Helpers/ApplyRegistryRegFile.ps1"
. "$PSScriptRoot/Scripts/Helpers/TestIfUserIsLoggedIn.ps1"
# Threading functions
@@ -401,7 +402,7 @@ else {
}
if ($script:Params.ContainsKey("Sysprep")) {
$defaultUserPath = GetUserDirectory -userName "Default"
GetUserDirectory -userName "Default" | Out-Null
# Exit script if run in Sysprep mode on Windows 10
if ($WinVersion -lt 22000) {
@@ -412,10 +413,10 @@ if ($script:Params.ContainsKey("Sysprep")) {
# Ensure that target user exists, if User or AppRemovalTarget parameter was provided
if ($script:Params.ContainsKey("User")) {
$userPath = GetUserDirectory -userName $script:Params.Item("User")
GetUserDirectory -userName $script:Params.Item("User") | Out-Null
}
if ($script:Params.ContainsKey("AppRemovalTarget")) {
$userPath = GetUserDirectory -userName $script:Params.Item("AppRemovalTarget")
GetUserDirectory -userName $script:Params.Item("AppRemovalTarget") | Out-Null
}
# Remove LastUsedSettings.json file if it exists and is empty