The first one is using the method RegRead from WScript.Shell.
If the given key is not found, it will rise an error, so we need to use an On Error Resume Next (which I don’t really like).
We would need to pass to the function a string like HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\ (note the trailing \) if we are looking for a Registry Key (those that look like a folder). If we want to check if a value inside a key exists, we would remove the trailing \, like HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\CurrentLevel.
Function RegKeyExists(Key)
Dim oShell, entry
On Error Resume Next
Set oShell = CreateObject("WScript.Shell")
entry = oShell.RegRead(Key)
If Err.Number <> 0 Then
Err.Clear
RegKeyExists = False
Else
Err.Clear
RegKeyExists = True
End If
End Function |
Function RegKeyExists(Key)
Dim oShell, entry
On Error Resume Next
Set oShell = CreateObject("WScript.Shell")
entry = oShell.RegRead(Key)
If Err.Number <> 0 Then
Err.Clear
RegKeyExists = False
Else
Err.Clear
RegKeyExists = True
End If
End Function
The second method uses WMI.
In this case, we would need to pass the Key Hive (Current User, Local Machine, etc) in the form of hex numbers (I declared them as constants). The KeyPath would be something like SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings.
Const HKCR = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Const HKUS = &H80000003 'HKEY_USERS
Const HKCC = &H80000005 'HKEY_CURRENT_CONFIG
Function KeyExists(Key, KeyPath)
Dim oReg: Set oReg = GetObject("winmgmts:!root/default:StdRegProv")
If oReg.EnumKey(Key, KeyPath, arrSubKeys) = 0 Then
KeyExists = True
Else
KeyExists = False
End If
End Function |
Const HKCR = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Const HKUS = &H80000003 'HKEY_USERS
Const HKCC = &H80000005 'HKEY_CURRENT_CONFIG
Function KeyExists(Key, KeyPath)
Dim oReg: Set oReg = GetObject("winmgmts:!root/default:StdRegProv")
If oReg.EnumKey(Key, KeyPath, arrSubKeys) = 0 Then
KeyExists = True
Else
KeyExists = False
End If
End Function
The difference with this function is that will only check for Registry Keys and not for values.