Wes Sayeed
Wes Sayeed

Reputation: 197

Best way to determine if function call was successful

Consider the following VBScript sample, which reads a value from the registry and converts a relative path string into an absolute path string:

On Error Resume Next

Set objShell = CreateObject("WScript.Shell")

strPath = Replace(objShell.RegRead(someRegKey),"\relative path","\\?\Absolute path",1,-1,1)

What's the best way to determine if the call to RegRead() succeeded? I know that RegRead() will raise an Err if the registry key does not exist.

Basically, if I use this construct in a VBScript, is it safe to simply check the value of Err.Number? Or do I need to test the resultant string? Or both?

I'm trying to not be overly verbose in my code, but in a broader sense I want to understand how VBScript handles these things.

Upvotes: 1

Views: 186

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200363

The best way is to not use RegRead (or nested function/method calls) in the first place. Use WMI (which will provide you with an actual return code) and separate the registry read from the replacement operation:

Const HKCU = &H80000001
Const HKLM = &H80000002

Set reg = GetObject("winmgmts://./root/default:StdRegProv")

hive = HKLM
key  = "SOFTWARE\foo"
valueName = "bar"

rc = reg.GetStringValue(hive, key, valueName, value)

If rc <> 0 Then
  WScript.Echo "Error reading " & key & "\" & valueName & ": " & rc
  WScript.Quit 1
End If

strPath = Replace(value, "\relative path", "\\?\Absolute path", 1, -1, 1)

Upvotes: 2

Related Questions