Skip to content

Instantly share code, notes, and snippets.

@rlabbe
Created February 12, 2024 19:37
Show Gist options
  • Save rlabbe/9d4a6f8b7a21c650543b8330c45fe813 to your computer and use it in GitHub Desktop.
Save rlabbe/9d4a6f8b7a21c650543b8330c45fe813 to your computer and use it in GitHub Desktop.
import os
import winreg
''' find all duplicate and invalid paths in your user account on windows'''
def expand_env_vars(paths: list[str]) -> list[str]:
return [os.path.expandvars(path) for path in paths]
def find_invalid_paths():
user_paths, system_paths = get_user_and_system_paths()
combined_paths = user_paths + system_paths
invalid_paths = []
for path in combined_paths:
if path and not os.path.exists(path):
if path in user_paths:
print(f"Invalid path '{path}' found in user-specific environment variables.")
elif path in system_paths:
print(f"Invalid path '{path}' found in system-wide environment variables.")
invalid_paths.append(path)
if not invalid_paths:
print("No invalid paths found.")
def find_duplicate_paths():
user_paths, system_paths = get_user_and_system_paths()
combined_paths = user_paths + system_paths
seen_paths = set()
duplicate_paths = set()
for path in combined_paths:
if path and path in seen_paths:
duplicate_paths.add(path)
else:
seen_paths.add(path)
if duplicate_paths:
for path in duplicate_paths:
if path in user_paths and path in system_paths:
print(f"Duplicate path '{path}' found in both user-specific and system-wide environment variables.")
elif path in user_paths:
print(f"Duplicate path '{path}' found in user-specific environment variables.")
elif path in system_paths:
print(f"Duplicate path '{path}' found in system-wide environment variables.")
else:
print("No duplicate paths found.")
def get_user_and_system_paths() -> tuple[list[str], list[str]]:
user_paths = []
user_env_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Environment')
try:
user_path_value, _ = winreg.QueryValueEx(user_env_key, 'Path')
user_paths = user_path_value.split(os.pathsep)
except FileNotFoundError:
pass
finally:
winreg.CloseKey(user_env_key)
system_paths = []
system_env_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')
try:
system_path_value, _ = winreg.QueryValueEx(system_env_key, 'Path')
system_paths = system_path_value.split(os.pathsep)
except FileNotFoundError:
pass
finally:
winreg.CloseKey(system_env_key)
user_paths = expand_env_vars(user_paths)
system_paths = expand_env_vars(system_paths)
return user_paths, system_paths
# Example usage:
print("Finding invalid paths:")
find_invalid_paths()
print("\nFinding duplicate paths:")
find_duplicate_paths()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment