I'll help you create a Python script to list and restore Windows system restore points using the Windows API. Here's a complete solution using the wmi library and subprocess for system restore operations:
import wmi
import subprocess
import sys
from datetime import datetime
class SystemRestoreManager:
def __init__(self):
try:
self.wmi_conn = wmi.WMI()
except Exception as e:
print(f"Error connecting to WMI: {e}")
sys.exit(1)
def list_restore_points(self):
"""List all available system restore points"""
try:
restore_points = self.wmi_conn.Win32_SystemRestore()
if not restore_points:
print("No system restore points found.")
return []
print("\nAvailable System Restore Points:")
print("-" * 80)
print(f"{'Index':<5} {'Sequence Number':<15} {'Description':<30} {'Creation Time':<20}")
print("-" * 80)
restore_point_list = []
for i, rp in enumerate(restore_points):
# Convert WMI datetime to readable format
creation_time = self._convert_wmi_time(rp.CreationTime)
print(f"{i+1:<5} {rp.SequenceNumber:<15} {rp.Description[:29]:<30} {creation_time:<20}")
restore_point_list.append({
'index': i + 1,
'sequence_number': rp.SequenceNumber,
'description': rp.Description,
'creation_time': creation_time,
'restore_point_type': rp.RestorePointType
})
print("-" * 80)
return restore_point_list
except Exception as e:
print(f"Error listing restore points: {e}")
return []
def _convert_wmi_time(self, wmi_time):
"""Convert WMI datetime format to readable string"""
try:
if wmi_time:
# WMI time format: YYYYMMDDHHMMSS.ffffff+UUU
time_str = wmi_time.split('.')[0]
dt = datetime.strptime(time_str, '%Y%m%d%H%M%S')
return dt.strftime('%Y-%m-%d %H:%M:%S')
return "Unknown"
except:
return "Unknown"
def create_restore_point(self, description="Manual Restore Point"):
"""Create a new system restore point before restoring"""
try:
print(f"Creating restore point: {description}")
# Use PowerShell to create restore point
ps_command = f'''
Checkpoint-Computer -Description "{description}" -RestorePointType "MODIFY_SETTINGS"
'''
result = subprocess.run([
'powershell', '-Command', ps_command
], capture_output=True, text=True, shell=True)
if result.returncode == 0:
print("Restore point created successfully.")
return True
else:
print(f"Failed to create restore point: {result.stderr}")
return False
except Exception as e:
print(f"Error creating restore point: {e}")
return False
def restore_system(self, sequence_number):
"""Restore system to specified restore point"""
try:
print(f"Initiating system restore to sequence number: {sequence_number}")
print("WARNING: This will restart your computer and restore system settings.")
confirm = input("Are you sure you want to proceed? (yes/no): ").lower().strip()
if confirm not in ['yes', 'y']:
print("System restore cancelled.")
return False
# Create a restore point before restoring
self.create_restore_point("Before System Restore")
# Use PowerShell to initiate system restore
ps_command = f'''
$restorePoint = Get-ComputerRestorePoint | Where-Object {{$_.SequenceNumber -eq {sequence_number}}}
if ($restorePoint) {{
Restore-Computer -RestorePoint $restorePoint.SequenceNumber -Confirm:$false
}} else {{
Write-Error "Restore point not found"
exit 1
}}
'''
print("Starting system restore... Your computer will restart.")
result = subprocess.run([
'powershell', '-Command', ps_command
], capture_output=True, text=True, shell=True)
if result.returncode == 0:
print("System restore initiated successfully.")
return True
else:
print(f"Failed to initiate system restore: {result.stderr}")
return False
except Exception as e:
print(f"Error during system restore: {e}")
return False
def run_interactive(self):
"""Run interactive system restore interface"""
print("Windows System Restore Manager")
print("=" * 40)
# Check if running as administrator
if not self._is_admin():
print("WARNING: This script should be run as Administrator for full functionality.")
print("Some operations may fail without administrator privileges.\n")
while True:
print("\nOptions:")
print("1. List restore points")
print("2. Create restore point")
print("3. Restore system")
print("4. Exit")
choice = input("\nEnter your choice (1-4): ").strip()
if choice == '1':
self.list_restore_points()
elif choice == '2':
description = input("Enter description for restore point: ").strip()
if not description:
description = "Manual Restore Point"
self.create_restore_point(description)
elif choice == '3':
restore_points = self.list_restore_points()
if restore_points:
try:
selection = int(input("\nEnter the index number of restore point to restore to: "))
if 1 <= selection <= len(restore_points):
selected_rp = restore_points[selection - 1]
print(f"\nSelected restore point:")
print(f"Description: {selected_rp['description']}")
print(f"Creation Time: {selected_rp['creation_time']}")
self.restore_system(selected_rp['sequence_number'])
else:
print("Invalid selection.")
except ValueError:
print("Please enter a valid number.")
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
def _is_admin(self):
"""Check if script is running with administrator privileges"""
try:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def main():
"""Main function to run the system restore manager"""
try:
manager = SystemRestoreManager()
manager.run_interactive()
except KeyboardInterrupt:
print("\n\nOperation cancelled by user.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
To use this script, you'll also need to install the required dependencies:
pip install wmi pywin32
Here's also a simpler version that focuses just on the core functionality:
import wmi
import subprocess
import sys
def list_restore_points():
"""Simple function to list restore points"""
try:
c = wmi.WMI()
restore_points = c.Win32_SystemRestore()
points = []
for rp in restore_points:
points.append({
'sequence': rp.SequenceNumber,
'description': rp.Description,
'creation_time': rp.CreationTime
})
return points
except Exception as e:
print(f"Error: {e}")
return []
def restore_to_point(sequence_number):
"""Restore to specific restore point"""
try:
cmd = f'powershell "Restore-Computer -RestorePoint {sequence_number} -Confirm:$false"'
subprocess.run(cmd, shell=True)
return True
except Exception as e:
print(f"Restore failed: {e}")
return False
# Example usage
if __name__ == "__main__":
points = list_restore_points()
for i, point in enumerate(points):
print(f"{i+1}. {point['description']} - {point['sequence']}")
Key features of this solution:
- Lists all available system restore points with details
- Creates new restore points before restoring (safety measure)
- Provides interactive interface for selecting restore points
- Uses PowerShell commands for actual restore operations
- Includes administrator privilege checking
- Handles errors gracefully
Important notes:
- Run the script as Administrator for full functionality
- System restore will restart your computer
- The script creates a safety restore point before restoring
- Make sure System Restore is enabled on your Windows 11 system
The script uses WMI to query restore points and PowerShell commands to perform the actual restore operations, which is the most reliable approach for Windows system restore functionality.