check if a registry key exists with WScript

人走茶凉 提交于 2019-12-04 09:53:35

You probably need to remove the trailing slash. If you use that, it will look for the default value for the key you have specified, and if it does not find it, will give that error.

Conversely, if you try to access a key as if it was a value by using no trailing slash, you will get the same error.

Some examples trying to access a key:

Fails:

var keyPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
var shell = new ActiveXObject("WScript.Shell");
var regValue = shell.RegRead(keyPath);
WScript.Echo("Value: " + regValue);

Succeeds (but gives empty result since Default value is empty):

var keyPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\";
var shell = new ActiveXObject("WScript.Shell");
var regValue = shell.RegRead(keyPath);
WScript.Echo("Value: " + regValue);

Some examples trying to access a value:

Succeeds (output is Value: C:\Program Files):

var keyPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ProgramFilesDir";
var shell = new ActiveXObject("WScript.Shell");
var regValue = shell.RegRead(keyPath);
WScript.Echo("Value: " + regValue);

Fails (shouldn't use trailing slash when accessing a value):

var keyPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ProgramFilesDir\\";
var shell = new ActiveXObject("WScript.Shell");
var regValue = shell.RegRead(keyPath);
WScript.Echo("Value: " + regValue);

you are trying to open HKLM hive and probably WScript (or user you start it) have no permissions for that
you can look on permissions with regedt32

shersha

What I got is ,

If the default value of the key is not been set then it will say unable to open registry key '---' for reading.

Now, if the key has a default value and you are not appending \\ after the key then also you will get the same error.

So, to get the default value you must add \\ , otherwise add the exact keyword listing under that key. e.g. "Version", "Location" etc.

vbscript with single back slash and trailing slash in the end for the key works for me:

On Error Resume Next 
Set WSHShell = CreateObject("WScript.Shell")
s = WSHShell.RegRead( "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Word\" )

if Err.Number <> 0 then
    MsgBox(Err.Description)
    MsgBox("Office is not installed?" )
    exit Function
Else    
    MsgBox("Office is installed")
    exit Function
    ''wscript.quit
End If
MsgBox("xxxxxxxxxxxxxxxxx")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!