Check if registry key exists using VBScript
Asked Answered
N

8

18

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.

Needlecraft answered 7/3, 2012 at 15:27 Comment(0)
N
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
Needlecraft answered 8/3, 2012 at 13:50 Comment(0)
D
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
Dioptric answered 28/11, 2012 at 22:40 Comment(3)
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 @NeedlecraftPantelleria
That page is still live when I check it.Dioptric
So it is. I must have managed to visit it during a momentary outage or something, sorry.Pantelleria
G
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.
Gasparo answered 20/2, 2013 at 17:12 Comment(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 = &H80000002Cromlech
@Cromlech Good point, have added the consts to avoid any confusion.Gasparo
Can someone please explain the 4th parameter? Thanks.Twofaced
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.Twofaced
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.Gasparo
A
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
Aluminize answered 2/8, 2016 at 15:4 Comment(0)
U
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
Underplay answered 7/3, 2012 at 15:32 Comment(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.DescriptionEscapade
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.Needlecraft
S
0

The Scripting Guy! Blog:

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

Now archived here:

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 exist.

Systematics answered 22/8, 2012 at 21:47 Comment(1)
The link is no longer valid, found it here devblogs.microsoft.com/scripting/…Twofaced
M
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
Milker answered 24/12, 2020 at 3:11 Comment(0)
T
0

I personally prefer to use the WMI method instead of the Shell method to avoid basing the function's result on error trapping as this can masquerade some edge cases. In addition, the WMI method can be used against a remote computer, which you can't do with Shell and it also offers additional capabilities that Shell doesn't, such as working with permissions in the Registry.

All the answers provided here that use the WMI method fail to detect the case were the registry key actually exists but the account the script is running under does not have read permissions on the key. So here is a function that accounts for this case.

Option Explicit

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

RegKeyExists HKLM, "SYSTEM\CurrentControlSet\Services\EventLog\Microsoft-Windows-Diagnostics-Performance/Operational"

WSH.Quit(0)

 Function RegKeyExists(ByVal Hive, ByVal RegKeyPath) 'As Boolean
'---------------------------------------------------------------

 Dim objStdRegProv
 Dim Result

 Set objStdRegProv = GetObject("winmgmts:!root/default:StdRegProv")
 Result = objStdRegProv.EnumValues(Hive, RegKeyPath)

 Select Case Result
  Case 0    : WSH.Echo "Key exists."
  Case 2    : WSH.Echo "Key does not exist."
  Case 5    : WSH.Echo "Key exists (Permission denied)."
  Case Else : WSH.Echo "Unhandled error (" & Hex(Result) & ")."
 End Select

 RegKeyExists = (Result = 0) Or (Result = 5)

 Set objStdRegProv = Nothing

End Function 'RegKeyExists
Twofaced answered 24/5, 2024 at 9:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.