Check if registry key exists using VBScript - windows

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.

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

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

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.

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

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

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.

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

Related

800A0408, 800A0400 errors [duplicate]

I am trying to create a registry key and subkey for enabling IE 11 enterprise mode for all users on a machine. This is what I am using for my VBScript currently and it is failing horribly (does not add the key). I could use some assistance in getting this corrected.
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set ObjRegistry = _
GetObject("winmgmts:{impersonationLevel = impersonate}! \\" & _
strComputer & "\root\default:StdRegProv")
strPath = strKeyPath & "\" & strSubPath
strKeyPath = "Software\Policies\Microsoft"
strSubPath = "Internet Explorer\Main\EnterpriseMode"
strName = "Enabled"
ObjRegistry.CreateKey (HKEY_LOCAL_MACHINE, strPath)
ObjRegistry.SetStringValue HKEY_LOCAL_MACHINE, strPath, strName, strValue
MsgBox "Successfully enabled Internet Explorer Enterprise Mode."
End Function
There are several issues with your code, aside from the fact that you posted an incomplete code sample.
"winmgmts:{impersonationLevel = impersonate}! \\" & strComputer & "\root\default:StdRegProv"
The WMI moniker contains a spurious space between security settings and path (...! \\...). Remove it.
As a side note, it's pointless to use a variable for the hostname if that hostname never changes.
strPath = strKeyPath & "\" & strSubPath
You define strPath before you define the variables you build the path from. Also, your path components are defined as string literals, so you could drop the concatenation and the additional variables and simply define strPath as a string literal.
ObjRegistry.CreateKey (HKEY_LOCAL_MACHINE, strPath)
You must not put argument lists in parentheses unless you're calling the function/method/procedure in a subexpression context. See here for more details. However, you may want to check the return value of your method calls to see if they were successful.
And FTR, hungarian notation is pointless code bloat. Don't use it.
Modified code:
Function SetEnterpriseMode(value)
Const HKLM = &h80000002
Set reg = GetObject("winmgmts:{impersonationLevel=impersonate}!//./root/default:StdRegProv")
path = "Software\Policies\Microsoft\Internet Explorer\Main\EnterpriseMode"
name = "Enabled"
rc = reg.CreateKey(HKLM, path)
If rc <> 0 Then
MsgBox "Cannot create key (" & rc & ")."
Exit Function
End If
rc = reg.SetStringValue(HKLM, path, name, value)
If rc = 0 Then
MsgBox "Successfully enabled Internet Explorer Enterprise Mode."
Else
MsgBox "Cannot set value (" & rc & ")."
End If
End Function

add multiple multi string values to registry using array

Code is cleaned and changed from previous post since old logics had various errors that have been corrected and narrowed down to one error in one condition that I cant find an answer to. Currently getting error when my url is being read as only value and throwing Subscript Out of range error even though array is initialized. Other conditions when user has preset items or no key at all works perfectly. Thanks.
option explicit
'on error resume next
Dim ObjName,oADSysInfo,strComputer
Dim objReg,IE_Main,mstrValName,strFunctionIntranet,strNYHomepage,multiStringValues(),allURLs(),itemname,a,return
Set oADSysInfo = CreateObject("ADSystemInfo")
Set ObjName = GetObject("LDAP://" & oADSysInfo.UserName)
strComputer = "."
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
Const HKCU = &H80000001
IE_Main = "Software\Microsoft\Internet Explorer\Main"
mstrValName = "Secondary Start Pages"
strNYHomepage = "http://www.google.com"
strFunctionIntranet = "www.mycompany.com"
SetHomePage
Sub SetHomepage
objReg.setStringValue HKCU,IE_Main,"Start Page",strNYHomepage
'Reading MultiStringValue of "Secondary Start Pages" for HKCU and continuing if it has something preset.
return = objReg.getMultiStringValue (HKCU,IE_Main,mstrValName,multiStringValues)
If return=0 Then
a=0
'Reading all items currently set to make sure users retain their existing URLs.
For Each itemname In multiStringValues
'Only continue if any of the existing URLs DO NOT MATCH what we are enforcing as the URL.
If itemname <> strFunctionIntranet Then
WScript.Echo itemname
WScript.Echo "itemname is NOT equal intranet"
a = a + 1
ReDim Preserve allURLs(a)
allURLs(a) = itemname
'a = a + 1
End If
Next
objReg.DeleteValue HKCU,IE_Main,mstrValName
'Enforce our URL to always be the first item.
allURLs(0)=strFunctionIntranet
'Set the new MultiStringValue registry key back.
objReg.setMultiStringValue HKCU,IE_Main,mstrValName,allURLs
WScript.echo "finished setting all secondary tabs... "
Else
strFunctionIntranet = Array(strFunctionIntranet)
objReg.setMultiStringValue HKCU,IE_Main,mstrValName,strFunctionIntranet
End If
End Sub
Wscript.Quit
Your array contains an empty element, because you create it one field too big.
Change this line:
ReDim Preserve allURLs(a+1)
into this:
ReDim Preserve allURLs(a)

Checking registry value

Added the following lines to a verification script to check if Registry Value has been added and getting message
Error occored while verifying the Registry Value for HKLM\SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR
Here is the code:
Dim strRegvalue
strRegvalue = g_objShell.RegRead("HKLM\SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR\")
If LCase(strRegvalue) = "True" Then
Call WriteToLog("HKLM\SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR value verified successfully")
Else
RegSuccessCode = 111
Call WriteToLog("Error occurred while verifying the Registry Value for HKLM\SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR")
End If
Could you let me know where I'm going wrong with this.
If you want to use RegRead to check for the existence of a registry key, you can do so by reading the key's default value. However, you must enable error handling then, because RegRead will raise an error if the value cannot be read (i.e. the key doesn't exist):
key = "HKLM\SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR\"
On Error Resume Next
g_objShell.RegRead key
If Err Then
WScript.Echo key & " does not exist."
Else
WScript.Echo key & " exists."
End If
On Error Goto 0
A better way would be to use the WMI registry methods, for instance EnumKey:
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
Const HKLM = &h80000002
key = "SOFTWARE\OLEforRetail\ServiceOPOS\MSR\REDIRON_MSR\"
retval = reg.EnumKey(HKLM, key, Null)
If retval = 0 Then
WScript.Echo key & " exists."
Else
WScript.Echo key & " does not exist."
End If

Specific Registry Key can't be found with VBScript

For a Test automation I have to check if certain Keys are generated in the registry.
By far I have this script:
'Registry Path
Const HKCR = &H80000000 'HKEY_CLASSES_ROOT (0)
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE (1)
Dim oReg: Set oReg = GetObject("winmgmts:!root/default:StdRegProv")
'Dim Arrays
Dim RegRootArray(1)
Dim RegMachineArray(6)
Dim CurrentArray()
'HKEY_CLASSES_ROOT Array
RegRootArray(0) = "AlmBtPgLib.ALMPlugIn.1\CLSID"
RegRootArray(1) = "AlmBtPgLib.ALMPlugIn\CurVer"
'HKEY_LOCAL_MACHINE Array
RegMachineArray(0) = "SOFTWARE\Macrovision\FlexNet Publisher"
RegMachineArray(1) = "SOFTWARE\Company\SWS\PlugIns\AlmBtPgLib.ALMPlugIn"
RegMachineArray(2) = "SYSTEM\ControlSet001\services\FlexNet Licensing Service"
RegMachineArray(3) = "SYSTEM\CurrentControlSet\services\FlexNet Licensing Service"
RegMachineArray(4) = "SOFTWARE\Company\LMS"
RegMachineArray(5) = "SYSTEM\CurrentControlSet\services\aksfridge"
RegMachineArray(6) = "SYSTEM\CurrentControlSet\services\hasplms"
'Loop through both Arrays and check Registry
For i = 0 To 1
If i=0 Then
ReDim CurrentArray(UBound(RegRootArray)) 'Copy Values from RegRootArray to CurrentArray
For arrI1 = LBound(RegRootArray) To UBound(RegRootArray)
CurrentArray(arrI1) = RegRootArray(arrI1)
Next
Key = HKCR
Else
ReDim CurrentArray(UBound(RegMachineArray)) 'Copy Values from RegMachineArray to CurrentArray
For arrI2 = LBound(RegMachineArray) To UBound(RegMachineArray)
CurrentArray(arrI2) = RegMachineArray(arrI2)
Next
Key = HKLM
End If
'Check Keys in Registry
For Each Path In CurrentArray
If oReg.EnumKey(Key, Path, arrSubKeys) = 0 Then
MsgBox(Path & " exist") 'for development
Else
MsgBox(Path & " don't exist") 'for development
End If
Next
Next
For some reason
"SOFTWARE\Company\SWS\PlugIns\AlmBtPgLib.ALMPlugIn"
is shown as non existing.
I checked if PlugIns or SWS "exists".
None of them do. Company does exist.
I checked the registry and the path manually. Both seem to be okay.
When I create a new Key I can't find it neither.
I restarted the system, no change.
The return value of EnumKey is 2. Simply 2.
I searched the web but couldn't find a solution.
Thanks for your help.
I can't check anything util tomorrow because i leave work for the day.
Update:
When i run the script extern, say as checkReg.vbs it works.
Could it be that UFT somehow has not the right permission? Although both, the .vbs script and UFT run under the same User.
Cheers
sam
In scripting or Visual Basic, the method EnumKey returns an integer value that is 0 (zero) if successful. If the function fails, the return value is a nonzero error code according to Microsoft.
http://msdn.microsoft.com/en-us/library/aa390387%28v=vs.85%29.aspx
Should not you use something like this instead:
Set objReg = Server.CreateObject("WScript.Shell")
RegValue = objReg.RegRead(yourregistryentrypath)

Check if a binary registry value exists via VBScript

I have a code which checks for a registry key value that exists or not. It only works on none binary values, if the target path is a binary value then it can not checks for it and will tell that the key does not exists.
Here is the Code:
Const HKEY_CURRENT_USER = &H80000001
strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "System\CurrentControlSet\Control\Stranger"
strValueName = "TargetBinaryKey"
objRegistry.GetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,strValue
If IsNull(strValue) Then
WScript.Echo "The Key Does Not Exists."
Else
WScript.Echo "The Key Exists."
End If
What should I do?
You should use .enumValues instead of .GetStringValue. You can find a code snippet here
Addition: you could also use GetBinaryValue if you know at forehand that the value is stored as binary

Resources