Two ways to check if a Registry Key exists using VBScript

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

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
  EndIf
EndFunction

The difference with this function is that will only check for Registry Keys and not for values.

2 thoughts on “Two ways to check if a Registry Key exists using VBScript”

  1. I think the second method’s logic is backwards:

    If oReg.EnumKey(Key, KeyPath, arrSubKeys) = 0 Then
    KeyExists = False
    Else
    KeyExists = True
    End If

    tests showed that running KeyExists(HKLM,”SOFTWARE\ODBC\ODBC.INIddd”) was showing it exits when it clearly doesn’t.

  2. LOL
    Never mind it was the other logic in my script that was backwards…
    I didn’t realize that the return value was 0 for success.

Leave a Reply

Your email address will not be published. Required fields are marked *


− five = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>