Search code examples
vbscriptregistry

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.


Solution

  • 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