Skip to content

VBScript : How to delete a Windows’ registry key and all its subkeys

Option Explicit

Sub DeleteRegKeyAndSubKeys(strRegTree, strKeyPath)
'strRegTree = 	"HKEY_CLASSES_ROOT"
'				"HKEY_CURRENT_USER"
'				"HKEY_LOCAL_MACHINE"
'				"HKEY_USERS"
'				"HKEY_CURRENT_CONFIG"
'strKeyPath is the registry key to delete. Example :
'				"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MySoftware"

	Const HKEY_CLASSES_ROOT		= &H80000000
	Const HKEY_CURRENT_USER		= &H80000001
	Const HKEY_LOCAL_MACHINE	= &H80000002
	Const HKEY_USERS			= &H80000003
	Const HKEY_CURRENT_CONFIG	= &H80000005

	Dim hTree, strComputer, oReg, arrSubKeys, strSubKey

	Select Case strRegTree
		Case "HKEY_CLASSES_ROOT"	hTree = HKEY_CLASSES_ROOT
		Case "HKEY_CURRENT_USER"	hTree = HKEY_CURRENT_USER
		Case "HKEY_LOCAL_MACHINE"	hTree = HKEY_LOCAL_MACHINE
		Case "HKEY_USERS"			hTree = HKEY_USERS
		Case "HKEY_CURRENT_CONFIG"	hTree = HKEY_CURRENT_CONFIG
	End Select
	
	strComputer = "."
	Set oReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

    oReg.EnumKey hTree, strKeyPath, arrSubKeys 

    If IsArray(arrSubKeys) Then 
        For Each strSubKey In arrSubKeys 
            DeleteRegKeyAndSubKeys strRegTree, strKeyPath & "\" & strSubKey 
        Next 
    End If 

    oReg.DeleteKey hTree, strKeyPath 

End Sub

'DeleteRegKeyAndSubKeys "HKEY_LOCAL_MACHINE", "SOFTWARE\Classes\Installer\Products\B1E406903FD90804C9B350FA2EF723D4\"