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
Related
I want help to create a registry path which will use a variable for logged in user SID. The path is like - HKEY_USERS\'%UserSID%'\Software\Microsoft\Office\16.0\Outlook
User SID should be picked for whoever user is currently logged in on the system.
I don't know how to create this variable?
I want to use this variable in my script array.
KEY_PATHS = Array("HKEY_USERS\S-1-5-21-4054882774-118064744-2143271696-500\Software\Microsoft\Office\16.0\Outlook", _
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-2660683129-3636505375-3381148637-65620")
DEBUG_PRINTING = False
MASTER_EXECUTION
Sub MASTER_EXECUTION()
' WMI Class Management
MAINTAIN_WMI_CLASS()
' Registry Key Storage
For Each KEY_PATH In KEY_PATHS
STORE_KEYS(KEY_PATH)
Next
If Err.Number <> 0 Then
EVENT_WRITER "ERROR","Storing Registry Keys Failed " & Err.Number & " | " & Err.Description
Else
EVENT_WRITER "INFO", "Storing Registry Keys Completed Successfully"
End If
End Sub
Function CONVERT_HIVE(HIVE)
' Check and return a system name based on a friendly name
If UCase(HIVE) = "HKEY_LOCAL_MACHINE" Then
CONVERT_HIVE = &H80000002
ElseIf UCase(HIVE) = "HKEY_USERS" Then
CONVERT_HIVE = &H80000002
ElseIf UCase(HIVE) = "HKEY_CURRENT_CONFIG" Then
CONVERT_HIVE = &H80000005
Else
EVENT_WRITER "ERROR","Converting Hive " & HIVE & " failed - " & Err.Number & " | " & Err.Description
WScript.Quit
End If
End Function
I got my answer in one of Microsoft thread:
Below VB code will fetch logged in user sid and and we can use that variable for our purpose:
vbs code in image
'And the variable path i was looking for will be like
KEY_PATHS = Array("HKEY_USERS\" & Sid & "\Software\Microsoft\Office\16.0\Outlook\PST")
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)
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)
I need help with a script that would traverse through the registry for a particular value and once match is found delete the parent key. I have found a code but it does not work. I suspect that is in not traversing through the registry key for match.
Option Explicit
Const HKEY_LOCAL_MACHINE = &H80000002
Const cRegKeyStartingPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
Const cRegValueToFind = "Ossec HIDS"
Const cRegDataToMatch = "DisplayName"
Dim oReg, subkey, arrSubKeys, sCurrentKey, sCurrentValuePath, iDeletedCount
iDeletedCount = 0
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
oReg.EnumKey HKEY_LOCAL_MACHINE, cRegKeyStartingPath, arrSubKeys
On Error Resume Next
For Each subkey In arrSubKeys
If Err.Number = 0 Then 'in case the collection is empty
sCurrentKey = "HKLM\" & cRegKeyStartingPath & subkey
sCurrentValuePath = sCurrentKey & "\" & cRegValueToFind
If customRegRead(sCurrentValuePath) = cRegDataToMatch Then
WScript.Echo "Going to delete "&sCurrentKey
DeleteRegKey sCurrentKey&"\"
iDeletedCount = iDeletedCount + 1
End If
Else
iDeletedCount = -1
End If
Next
Select Case iDeletedCount
Case 0
WScript.Echo "No matching keys found"
Case -1
WScript.Echo "No subkeys found below HKLM\"&cRegKeyStartingPath
Case Else
WScript.Echo "Deleted " & iDeletedCount & " keys"
End Select
Function customRegRead(sRegValue)
Dim oShell
Dim sRegReturn
Set oShell = CreateObject("WScript.Shell")
On Error Resume Next
Err.Clear
sRegReturn = oShell.RegRead(sRegValue)
If Err.Number<>0 Then
customRegRead = "Failed To Read Value"
Else
customRegRead = sRegReturn
End If
End Function
Sub DeleteRegKey(sKey)
Dim oShell
Set oShell = CreateObject("Wscript.Shell")
oShell.RegDelete sKey
End Sub
If there is something cleaner/better please advise.
I'd suggest to remove all occurrences of On Error Resume Next and stick with WMI methods. Also your current code doesn't use recursion, so you can only find values in immediate subkeys of cRegKeyStartingPath. You'll need recursion for traversing a tree of arbitrary depth.
Use EnumValues to enumerate the values of a given key:
rc = reg.EnumValues(HKLM, key, names, types)
The method returns 0 on success, so you can check for errors by evaluating the return code. After the call finishes the variable names contains an array with the names of the values in key, or Null if the key did not contain any values (short of the default value, that is). So the code for checking if a particular value exists in a given key might look like this:
reg.EnumValues HKLM, key, names, types
If Not IsNull(names) Then
For Each name In names
If name = "foo" Then
reg.GetStringValue HKLM, key, name, data
If data = "bar" Then
'delete key here
Exit For
End If
End If
Next
End If
You can traverse the registry by enumerating the subkeys of a given key via EnumKey and recursing into those subkeys:
Sub TraverseRegistry(root, key)
reg.EnumKey root, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
TraverseRegistry root, key & "\" & sk
Next
End If
End Sub
To delete a key use the DeleteKey method. The information which key must be deleted is something you already have: it's the value of the variable key from the value enumeration routine when found is true. However, you can't delete a key that has subkeys, so you must delete those first. Something for which you can re-use the traversal routine from above:
Sub DelKey(root, key)
reg.EnumKey root, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
DelKey root, key & "\" & sk 'delete subkeys first
Next
End If
'at this point all subkeys have already been deleted, so we can
'now delete the parent key
reg.DeleteKey root, key
End Sub
Put everything together and you get something like this:
Const HKLM = &h80000002
Const StartKey = "SOFTWARE\Wow...ion\Uninstall"
Const SearchValue = "DisplayName"
Const MatchData = "Ossec HIDS"
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
FindAndDeleteKey HKLM, StartKey, SearchValue, MatchData
Sub FindAndDeleteKey(root, key, value, data)
reg.EnumValues HKLM, key, names, types
If Not IsNull(names) Then
For Each name In names
If name = value Then
reg.GetStringValue HKLM, key, name, regdata
If regdata = data Then
DelKey root, key
Exit Sub
End If
End If
Next
End If
'value not found in current key => continue search in subkeys
reg.EnumKey root, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
FindAndDeleteKey root, key & "\" & sk, value, data
Next
End If
End Sub
Sub DelKey(root, key)
reg.EnumKey root, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
DelKey root, key & "\" & sk 'delete subkeys first
Next
End If
'at this point all subkeys have already been deleted, so we can
'now delete the parent key
reg.DeleteKey root, key
End Sub
Since you're looking for a particular value with particular data you could even simplify FindAndDeleteKey() to this:
Sub FindAndDeleteKey(key)
'Try to read the value directly. If the value doesn't exist this will
'simply return a non-zero return code and set data to Null.
reg.GetStringValue HKLM, key, SearchValue, data
If Not IsNull(data) Then
'value does exist
If data = MatchData Then
DelKey HKLM, key
Exit Sub
End If
End If
'value not found in current key => continue search in subkeys
reg.EnumKey HKLM, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
FindAndDeleteKey key & "\" & sk
Next
End If
End Sub
Edit: Below is a version that generates some debug output. Run it in a command prompt via cscript debug_sample.vbs. Note that since you want to delete stuff in HKLM you must run the script "as Administrator" when UAC is enabled.
Const HKLM = &h80000002
Const StartKey = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
Const SearchValue = "DisplayName"
Const MatchData = "Ossec HIDS"
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
FindAndDeleteKey StartKey
Sub FindAndDeleteKey(key)
WScript.Echo "[HKLM\" & key & "]"
rc = reg.GetStringValue(HKLM, key, SearchValue, data)
If Not IsNull(data) Then
WScript.Echo """" & SearchValue & """=""" & data & """"
If data = MatchData Then
DelKey HKLM, key
Exit Sub
End If
Else
WScript.Echo "'" & SearchValue & "' not found in [HKLM\" & key & "], rc=" & rc
End If
reg.EnumKey HKLM, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
FindAndDeleteKey key & "\" & sk
Next
End If
End Sub
Sub DelKey(root, key)
reg.EnumKey root, key, subkeys
If Not IsNull(subkeys) Then
For Each sk In subkeys
DelKey root, key & "\" & sk
Next
End If
rc = reg.DeleteKey(root, key)
WScript.Echo "Deleting [HKLM\" & key & "], rc=" & rc
End Sub
I was able to reproduce a return code 6 (handle is invalid) with an invalid hDefKey value, e.g. &h8000002 (only 7 digits) or h80000002 (missing ampersand).
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