In a newly installed system, whether its win10 or win11, the script works well.
After some trying, i believe its mainly because of some app changes some related registry, because when i uninstalled some app, the problem gone, and sadly, i was not aware of which may cause the problem and had not keep a backup of my registry.
I did write a python script try to find which registry is the cause, if you have the same problem, maybe consider using it to find the answer, and dont forget to let me know it.
import winreg
import os
import subprocess
from typing import Dict, Tuple, List
import logging
from datetime import datetime
def setup_logging():
"""Setup logging configuration"""
log_file = f'reg_restore_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8'),
logging.StreamHandler()
]
)
logging.info('Starting registry restoration program')
def parse_reg_file(file_path: str) -> Dict[str, Dict[str, str]]:
"""Parse reg file and return registry data in dictionary format"""
logging.info(f'Starting to parse registry file: {file_path}')
reg_data = {}
current_key = ""
try:
with open(file_path, 'r', encoding='utf-16') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if line.startswith('['):
current_key = line[1:-1]
reg_data[current_key] = {}
logging.debug(f'Found registry key: {current_key}')
elif '=' in line:
name, value = line.split('=', 1)
reg_data[current_key][name] = value
logging.debug(f'Key-value pair: {name} = {value}')
except Exception as e:
logging.error(f'Error parsing file {file_path}: {str(e)}')
raise
logging.info(f'Successfully parsed file {file_path}, contains {len(reg_data)} keys')
return reg_data
def compare_reg_files(prod_data: Dict, dev_data: Dict) -> List[Tuple[str, str, str, str]]:
"""Compare differences between two registry files"""
logging.info('Starting to compare registry file differences')
differences = []
for key in prod_data:
if key not in dev_data:
logging.info(f'Found new key: {key}')
for name, value in prod_data[key].items():
differences.append((key, name, value, 'add_key'))
logging.debug(f'Need to add: {key}\\{name} = {value}')
else:
for name, value in prod_data[key].items():
if name not in dev_data[key] or dev_data[key][name] != value:
differences.append((key, name, value, 'update_value'))
logging.info(f'Found different value: {key}\\{name}')
logging.debug(f'prod value: {value}')
logging.debug(f'dev value: {dev_data[key].get(name, "does not exist")}')
logging.info(f'Comparison completed, found {len(differences)} differences')
return differences
def apply_reg_entry(key: str, name: str, value: str, action: str) -> bool:
"""Apply single registry entry"""
logging.info(f'Applying registry entry: {key}\\{name}')
temp_reg_file = 'temp.reg'
try:
with open(temp_reg_file, 'w', encoding='utf-16') as f:
f.write('Windows Registry Editor Version 5.00\n\n')
f.write(f'[{key}]\n')
f.write(f'"{name}"={value}\n')
logging.debug(f'Temporary reg file created: {temp_reg_file}')
subprocess.run(['regedit', '/s', temp_reg_file], check=True)
logging.info('Registry entry applied successfully')
os.remove(temp_reg_file)
return True
except subprocess.CalledProcessError as e:
logging.error(f'Failed to apply registry entry: {str(e)}')
if os.path.exists(temp_reg_file):
os.remove(temp_reg_file)
return False
except Exception as e:
logging.error(f'Unexpected error occurred: {str(e)}')
if os.path.exists(temp_reg_file):
os.remove(temp_reg_file)
return False
def verify_reg_entry(key: str, name: str, value: str) -> bool:
"""Verify if registry entry is correctly applied
Implementation of verification logic needed based on specific requirements
"""
# TODO: Implement specific verification logic
return True
def save_failed_entry(key: str, name: str, value: str, output_file: str):
"""Save failed registry entries to new reg file"""
logging.info(f'Saving failed registry entry to file: {output_file}')
try:
with open(output_file, 'a', encoding='utf-16') as f:
if f.tell() == 0:
f.write('Windows Registry Editor Version 5.00\n\n')
f.write(f'[{key}]\n')
f.write(f'"{name}"={value}\n\n')
logging.info('Save successful')
except Exception as e:
logging.error(f'Error while saving failed entry: {str(e)}')
def main():
setup_logging()
logging.info('='*50)
logging.info('Program execution started')
try:
# Check if files exist
for file in ['prod.reg', 'dev.reg']:
if not os.path.exists(file):
logging.error(f'File not found: {file}')
return
# Read registry files
logging.info('Starting to read registry files')
prod_data = parse_reg_file('prod.reg')
dev_data = parse_reg_file('dev.reg')
# Compare differences
differences = compare_reg_files(prod_data, dev_data)
# Process each different registry entry
failed_reg_file = 'failed_entries.reg'
if os.path.exists(failed_reg_file):
logging.info(f'Deleting existing failed entries file: {failed_reg_file}')
os.remove(failed_reg_file)
total = len(differences)
success = 0
failed = 0
for i, (key, name, value, action) in enumerate(differences, 1):
logging.info(f'Processing entry {i}/{total}')
if apply_reg_entry(key, name, value, action):
if verify_reg_entry(key, name, value):
success += 1
logging.info('Verification successful')
else:
failed += 1
logging.warning('Verification failed')
save_failed_entry(key, name, value, failed_reg_file)
else:
failed += 1
save_failed_entry(key, name, value, failed_reg_file)
logging.info('='*50)
logging.info(f'Execution completed: Total {total} entries, {success} successful, {failed} failed')
if failed > 0:
logging.info(f'Failed entries saved to: {failed_reg_file}')
except Exception as e:
logging.error(f'Error occurred during program execution: {str(e)}')
raise
if __name__ == '__main__':
main()