17

I thought this would be easy, but apparently nobody does it... I'm trying to see if a registry key exists. I don't care if there are any values inside of it such as (Default).

This is what I've been trying.

Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
objRegistry.GetStringValue &H80000003,".DEFAULT\Network","",regValue

If IsEmpty(regValue) Then
    Wscript.Echo "The registry key does not exist."
Else
    Wscript.Echo "The registry key exists."
End If

I only want to know if HKEY_USERES\.DEFAULT\.Network exists. Anything I find when searching mostly seems to discuss manipulating them and pretty much assumes the key does exists since it's magically created if it doesn't.

0

7 Answers 7

13

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if
9

The second of the two methods here does what you're wanting. I've just used it (after finding no success in this thread) and it's worked for me.

http://yorch.org/2011/10/two-ways-to-check-if-a-registry-key-exists-using-vbscript/

The code:

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
3
  • 1
    For the curious, the link above is dead and I can't find a cached page; a copy of it appears to be here, but the other way is just the answer given by @MTeck
    – Kodithic
    Oct 7, 2016 at 2:54
  • 2
    That page is still live when I check it.
    – chris_k
    Jan 19, 2017 at 0:25
  • So it is. I must have managed to visit it during a momentary outage or something, sorry.
    – Kodithic
    Jan 19, 2017 at 6:01
9

Simplest way avoiding RegRead and error handling tricks. Optional friendly consts for the registry:

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

Then check with:

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")

If oReg.EnumKey(HKEY_LOCAL_MACHINE, "SYSTEM\Example\Key\", "") = 0 Then
  MsgBox "Key Exists"
Else
  MsgBox "Key Not Found"
End If

IMPORTANT NOTES FOR THE ABOVE:

  • Equals zero means the key EXISTS.
  • The slash after key name is optional and not required.
5
  • One more important note: If using HKEY_LOCAL_MACHINE as the first parameter, set a constant prior to the IF statement like this: Const HKEY_LOCAL_MACHINE = &H80000002
    – Beems
    Nov 16, 2016 at 17:02
  • @Beems Good point, have added the consts to avoid any confusion.
    – WhoIsRich
    Nov 16, 2016 at 17:57
  • Can someone please explain the 4th parameter? Thanks.
    – Safwan
    Dec 1, 2018 at 6:02
  • 1
    Per Microsoft's documentation there is no 4th parameter, I tested using a variable as the 4th parameter and nothing was returned. I also tested to add a 5th parameter and the code ran without any errors, it seems that any additional parameters you add at the end are simply ignored. The code also works fine if you omit the 3rd parameter.
    – Safwan
    Mar 19, 2022 at 22:30
  • Posted this a long time ago, so it was probably blindly repeated from an an old tutorial, so have removed the empty 4th param to avoid confusion.
    – WhoIsRich
    Mar 21, 2022 at 12:06
2

In case anyone else runs into this, I took WhoIsRich's example and modified it a bit. When calling ReadReg I needed to do the following: ReadReg("App", "HKEY_CURRENT_USER\App\Version") which would then be able to read the version number from the registry, if it existed. I also am using HKCU since it does not require admin privileges to write to.

Function ReadReg(RegKey, RegPath)
      Const HKEY_CURRENT_USER = &H80000001
      Dim objRegistry, oReg
      Set objRegistry = CreateObject("Wscript.shell")
      Set oReg = GetObject("winmgmts:!root\default:StdRegProv")

      if oReg.EnumKey(HKEY_CURRENT_USER, RegKey) = 0 Then
        ReadReg = objRegistry.RegRead(RegPath)
      else
        ReadReg = ""
      end if
End Function
1

edit (sorry I thought you wanted VBA).

Anytime you try to read a non-existent value from the registry, you get back a Null. Thus all you have to do is check for a Null value.

Use IsNull not IsEmpty.

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & _ 
    strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "Test Value"
objRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

If IsNull(strValue) Then
    Wscript.Echo "The registry key does not exist."
Else
    Wscript.Echo "The registry key exists."
End If
2
  • In contrary to VBA, On Error Goto {label} does not work on VBScript, but you can use On Error Resume Next and read out the err object by err.Number or err.Description Mar 7, 2012 at 15:40
  • 1
    This doesn't get what I need. I need to know if the key exists. Not the Value:Data pair. Testing against the default value "" would be fine. However, the copy/paste you provided that's easily found in a search does not make any distinction of whether or not the value exists, is empty, or is null. I need to know if just the key exists.
    – MTeck
    Mar 7, 2012 at 15:45
0

See the Scripting Guy! Blog:

How Can I Tell Whether a Value Exists in the Registry?

They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.

With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):

If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.

If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.

0

The accepted answer is too long, other answers didn't work for me. I'm gonna leave this for future purpose.

Dim sKey, bFound
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\SecurityHealth"

with CreateObject("WScript.Shell")
  on error resume next            ' turn off error trapping
    sValue = .regread(sKey)       ' read attempt
    bFound = (err.number = 0)     ' test for success
  on error goto 0                 ' restore error trapping
end with

If bFound Then
  MsgBox = "Registry Key Exist."
Else
  MsgBox = "Nope, it doesn't exist."
End If

Here's the list of the Registry Tree, choose your own base on your current task.

HKCR = HKEY_CLASSES_ROOT
HKCU = HKEY_CURRENT_USER
HKLM = HKEY_LOCAL_MACHINE
HKUS = HKEY_USERS
HKCC = HKEY_CURRENT_CONFIG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.