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
    RegKeyExists = False
    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 HKUS = &H80000003 'HKEY_USERS
Function KeyExists(Key, KeyPath)
  Dim oReg: Set oReg = GetObject("winmgmts:!root/default:StdRegProv")
  If oReg.EnumKey(Key, KeyPath, arrSubKeys) = 0 Then
    KeyExists = True
    KeyExists = False

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

One thought on “Two ways to check if a Registry Key exists using VBScript”

  1. Could you actually put where you would input the registry path? It doesn’t actually say it and I’m struggling trying to fit it in.

    I actually have a working copy with another method but the problem is I need to check for 3 keys. At the first step of the query it adds “On error resume next”. This works great for the first key but… Then when you get to the next key, Resume Next is already on so I can’t tell if I’m getting a false result.

    I didn’t include all 3 items to make the post to convoluted but here is one of the 3…

    ‘ Read MSWord6.wpc 64 Bit OS
    On Error Resume Next
    strMsWord = objShell.RegRead(“HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node” _
    & “\Microsoft\Shared Tools\Text Converters\Import\MSWord6.wpc”)
    If strMsWord = “” Then
    strMsWord = “This is Not Set”
    End If

    ‘ MSWord 64 Switch Default
    strMsWord = objShell.RegRead(“HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node” _
    & “\Microsoft\Shared Tools\Text Converters\Import\MSWord6.wpc”)
    If strMsWordSwitch = “0” Then
    strMsWordSwitchLevel = “0 = Add Default Gateway Default”
    ElseIf strMsWordSwitch = “1” Then
    strMsWordSwitchLevel = “1 = Dont Add Default Gateway Default”
    End If

    Thank you,

Leave a Reply

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

Are you human? *