Skip to content

Instantly share code, notes, and snippets.

@kaecy
Last active June 13, 2023 11:49
Show Gist options
  • Save kaecy/29b2bc88534f4c4d5d6c6b36f4f2e439 to your computer and use it in GitHub Desktop.
Save kaecy/29b2bc88534f4c4d5d6c6b36f4f2e439 to your computer and use it in GitHub Desktop.
Delete a registry key and all the keys under it.

Readme

> delete_key.py

Deleting these keys:
[
  software\classes\.test,
  software\classes\.test\New Key #1,
  software\classes\.test\shell,
  software\classes\.test\shell\open
]
Continue? (type "yes" to continue) yes
Deleting: software\classes\.test\shell\open
Deleting: software\classes\.test\shell
Deleting: software\classes\.test\New Key #1
Deleting: software\classes\.test
import winreg
class RegKey:
def __init__(self, parentkey, handle, keyname):
self.parentkey = parentkey
self.handle = handle
self.keyname = keyname
def enum_keys(self):
keys = []
i = 0
while True:
try:
childkeyname = winreg.EnumKey(self.handle, i)
childkey = open_key(self, childkeyname)
children, _, _ = winreg.QueryInfoKey(childkey.handle)
keys.append(childkey.keyname)
if children > 0:
keys.extend(childkey.enum_keys())
i += 1
except WindowsError:
return keys
def delete(self):
subkeys = self.enum_keys()
keys = [self.keyname]
keys.extend(subkeys)
print("Deleting these keys:")
print_list(keys)
answer = input("Continue? (type \"yes\" to continue) ")
if answer == "yes":
for i in range(len(keys)-1, -1, -1):
print("Deleting: " + keys[i])
winreg.DeleteKey(self.parentkey, keys[i])
def open_key(parent, child):
if type(parent) == RegKey:
handle = winreg.OpenKey(parent.handle, child)
child = parent.keyname + "\\" + child
else:
handle = winreg.OpenKey(parent, child)
return RegKey(parent, handle, child)
def print_list(keys):
print("[\n " + keys[0], end="")
for ext in keys[1:]:
print(",\n " + ext, end="")
print("\n]")
if __name__ == "__main__":
fileExtentionKey = open_key(winreg.HKEY_CURRENT_USER, r"software\classes\.test")
fileExtKey.delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment