Vbs как перейти к ключу в реестре

от admin

VBscript ,writing into registry

when i execute the code it always gave an error, ‘Invalid Root in Registry’ whats wrong with the code could somebody explain this ?

2 Answers 2

Try «HKEY_LOCAL_MACHINE» instead of HKLM. «HKEY_CURRENT_USER» instead of HKCU.

There are three arguments regarding registery write in vbs . For more information please head towards https://www.vbsedit.com/html/678e6992-ddc4-4333-a78c-6415c9ebcc77.asp

Problem is that you are not referring the size of registery i.e REG_SZ, DWORD , QWORD etc.

boga khan's user avatar

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Vbs как перейти к ключу в реестре

This is only a brief introduction to using VBScript to read and edit the registry. VBScript is based on Microsoft’s Visual Basic.

There are other alternatives including JScript, Console Registry Tool reg.exe and inf files for editing the registry. These are all powerful methods to edit the registry and VBS and JS are used in hijacking your Windows and IE settings, including locking the registry. Thus you can use a script to unlock your registry, as logon scripts and automate repetitive tasks in deployment. Refer to my article on "lock registry" for more details on unlocking regedit.

Windows XP’s Windows Script Host supports VBScript (and JScript). Just save the text file created in Notepad as vbs and double-click to run it. You can also use the command line version cscript.exe. Your third party security tools (e.g. Script Defender and anti-virus) should pop up warnings about malicious script and offer to stop it. If you know the script is safe then click OK or allow to run it.

If you wish to learn more about VBS and shell objects, read some books and online tutorials. But you can quickly learn the VBS syntax to edit the registry without learning VBS in great detail, as you’ll find out here.

2. The shell objects

The three shell objects for the registry are: RegRead, RegWrite and RegDelete. Not all data values are supported and binary values pose difficulties which will be explained below.

In the following syntax, strName refers to the key or value in quotation marks. Use a full path or a standard abbreviation (HKCR,HKCU, HKLM; the rest full path only). The path that ends with a \ indicates a key and that which ends with a value name a value name.

"HKCU\Testing\Subkey\" refers to the key or the default value of the key; and

"HKCU\Testing\Subkey\My Documents" refers to the value name My Documents of the Subkey key.

Be careful when trying out scripts. Open regedit so you can track what is happening. Back up adequately beforehand. Always test your scripts thoroughly.

2.1. RegWrite

Object.RegWrite( strName, anyvalue [,strType])

The RegWrite cannot write to REG_MULTI_SZ strings and is limited to writing only four bytes or one DWORD in REG_BINARY.

The following simple VBS will create four registry subkeys with different string types within a test key in the HKCU hive. For clarity I’ve separated the codes with line breaks. There is no prompt (except your anti-virus’) or confirmation dialogue.

The first line of code defines the shell object. The first RegWrite code writes a default value to the subkey. If the key is absent it will create it. If it is already present but has a different value it will change it. The second code is all in one line (as indicated by _).

Set Shell = CreateObject( "WScript.Shell" )

Shell.RegWrite "HKCU\Testing\Subkey\", 0, "REG_DWORD"

Shell.RegWrite "HKCU\Testing\Subkey\My Documents",_ "%USERPROFILE%\My Documents", "REG_EXPAND_SZ"

Shell.RegWrite "HKCU\Testing\Subkey\ValueName", "Hello", "REG_SZ"

Shell.RegWrite "HKCU\Testing\Subkey\ValueName2", 1, "REG_BINARY"

You can also use this WshShell object format:

Set WshShell = CreateObject( "WScript.Shell" )

WshShell.RegWrite "HKCU\Testing\Subkey\", 0, "REG_DWORD"
WshShell.RegWrite "HKCU\Testing\Subkey\My Documents", "%USERPROFILE%\My Documents", "REG_EXPAND_SZ"
WshShell.RegWrite "HKCU\Testing\Subkey\ValueName",_ "Hello", "REG_SZ"
WshShell.RegWrite "HKCU\Testing\Subkey\ValueName2", 1,_ "REG_BINARY"

The resulting key in the registry is shown here (fig. 1).

new registry key

Fig. 1. The new registry key created with the above scripts. Note the binary value has four bytes only.

2.2. RegRead

Object.RegRead (strName)

If the key name is specified, RegRead reads its default value. If the key is absent it returns an error.

The following script reads the above registry key except the binary value. Unlike the other two objects, you need to enclose the path in parenthesis.

Set WshShell = CreateObject( "WScript.Shell" )

Wscript.Echo WshShell.RegRead( "HKCU\Testing\Subkey\" )
Wscript.Echo WshShell.RegRead( "HKCU\Testing\Subkey\My_ Documents" )
Wscript.Echo WshShell.RegRead(_
"HKCU\Testing\Subkey\ValueName" )

The Echo object display the value in a WSH window one by one. The first echo gives this (fig. 2).

WSH message box showing 0.

Fig. 2. WSH message box showing 0.

You can add a meaningful sentence for the value and echo all three together (fig. 3) with a modified script like this.

Set WshShell = CreateObject( "WScript.Shell" )
a = WshShell.RegRead ( "HKCU\Testing\Subkey\" )
b = WshShell.RegRead (
"HKCU\Testing\Subkey\_My Documents" )
c = WshShell.RegRead ( "HKCU\Testing\Subkey\ValueName" )

Wscript.Echo "The HKCU\Testing\Subkey’s default value is", a, ",", "the My Documents value is", b, ",", "the ValueName is", c, "."

WSH message box with full message reading all 3 keys

Fig. 3. WSH message box with full message reading all three keys.

You can also find another example of my VBS to read and unlock the registry if it is disabled; see this article for details. Download and examine the script.

2.2.1. RegRead REG_BINARY values

To read binary values (binary or hexadecimal data), the script need to read and join the array.

The follow script reads this registry key:

HKEY_CURRENT_USER\Software\Microsoft\
Windows\CurrentVersion\Policies\Explorer

NoDriveTypeAutoRun

REG_BINARY = 5f 00 00 00

Set Shell = CreateObject("WScript.Shell")
arr = Shell.RegRead("HKCU\Software\Microsoft\Windows\_
CurrentVersion\Policies\Explorer\NoDriveTypeAutoRun")

For I = LBound(arr) To UBound(arr)
a(I) = CInt(arr(I))
b(I) = Hex (CInt(arr(I)))
Next

Wscript.Echo "The registry key name’s decimal value is", Join(a),",", "the hex value is", Join(b),"."

msgbox Join(a),,"The decimal value is"
msgbox Join(b),,"The hexadecimal value is"

You can customise the message box. The Wscript.Echo object above gives you this output (Fig. 4) bearing in mind that 5f is 95 in decimal (5×16+15):

WSH message box giving the reg key

Fig. 4. WSH message box giving the registry key’s decimal and hex values in the array.

The msgbox gives you these two in turn (Fig. 5 and 6):

WSH message box giving decimal value of 95

Fig. 5. WSH box giving the decimal value of 95 in the array.

WSH message box giving hex value of 5f

Fig. 6. WSH box giving the hex value of 5F in the array.

This is another way to do it, this time reading another hex key.

Set Shell = CreateObject("WScript.Shell")
arrRegValue = Shell.RegRead("HKCU\Software\Microsoft\Internet Explorer\Document Windows\Width")

Wscript.Echo "The registry key name’s hexadecimal value is", strRegValue

Private Function StrPad(Unpadded, Length, Padding)
StrPad = String((Length-Len(Unpadded)), Padding) & Unpadded
End Function

2.3. RegDelete

Object.RegDelete(strName)

Be very careful with this as there is no prompt or undo. Only the key or value name is needed, not the data or string type.

Читать:
Какие драйвера нужны для acer nitro 5

This VBS deletes the ValueName (Hello) from the above Testing key.

Set Shell = CreateObject( "WScript.Shell" )

This VBS deletes the following subkey "Subkey" with all the contents under it leaving the Testing key intact.

Set Shell = CreateObject( "WScript.Shell" )

Reference

Honeycutt, Jerry, Microsoft Windows XP Registry Guide (Redmond: Microsoft Press, 2003)

Knittel, Brian, Windows XP Under the Hood. Hardcore Windows Scripting and Command Line Power (Indianapolis: Que, 2003)

The Microsoft Windows Resource Kit Scripting Team, Windows 2000 Scripting Guide (Redmond: Microsoft Press, 2003)

Go to TOP

A special thanks to those people who assisted me in public forums regarding RegRead binary data.

Copyright � 2003-2005 by Kilian. All my articles including graphics are provided "as is" without warranties of any kind. I hereby disclaim all warranties with regard to the information provided. In no event shall I be liable for any damage of any kind whatsoever resulting from the information. The articles are provided in good faith and after some degree of verification but they may contain technical or typographical errors. Links to other web resources may be changed at any time and are beyond the control of the author. Articles may be added, removed, edited or improved at any time. No support is provided by the author.

This is not an official support page for any products mentioned. All the products mentioned are trademarks of their companies. Edit the registry at your own risk and back up first.

How to add a registry key using VBScript?

I want to add a registry key (DWORD=1) in HKEY_LOCAL_MACHINE \SYSTEM\CurrentControlSet\Control\StorageDevicePolicies using VBScript. How can I do that?

I say Reinstate Monica's user avatar

2 Answers 2

An example of registry entry creation would be:

where the targets can be changed accordingly to your needs.

Example 1: Set the registry flag to display Hidden and System files in Windows Explorer:

Example 2: Set the registry flag to hide Hidden and System files in Windows Explorer (the default):

Example 3: Create a «default value» at KCU\KeyName\
Note: The trailing backslash is required:

Vbs как перейти к ключу в реестре

REG QUERY не подойдет? Он может возвращать значение 0 или 1, которое потом можно обрабатывать.

Проверку осуществить можно так:

On error resume next
set oshell=createobject("WScript.shell")
value=oshell.regread ("HKCU\environment\test")
if err.number<>0 then wscript.echo "Нет нужного ключа" else wscript.echo "Есть нужный ключ"
wscript.echo value

Вместо HKCU\environment\test поставить нужный ключ.

Для добавления ключа можно использовать regwrite. Только у vbs есть некоторые ограничения: значения типа reg_bin, reg_milti_sz, reg_expand_sz не создает (или создает, только я не знаю как ). Так что для создания или перезаписи существующих значений лучше использовать импорт заготовленного reg-файлика:

oshell.Run "regedit.exe /s путь_к_reg-файлу",,true

Option Explicit
Dim i,Shell,KeyValue,Keys(1,4)
set Shell = WScript.CreateObject("WScript.Shell")
Keys(0,0)="ИмяКлюча"
Keys(0,1)="ВеткаРеестра"
Keys(0,2)="Значение"
Keys(0,3)="Тип"

On Error Resume Next
For i=0 To UBOUND(Keys)-1
Shell.RegRead(Keys(i,1)&Keys(i,0))
if Err.Source="WshShell.RegRead" then
Shell.RegWrite Keys(i,1)&Keys(i,0),Keys(i,2),Keys(i,3)
KeyValue=Keys(i,2)
else
KeyValue= Shell.RegRead(Keys(i,1)&"\"&Keys(i,0))
end if
Err.Clear
If KeyValue<>Keys(i,2) then
Shell.RegDelete(Keys(i,1)&"\"&Keys(i,0))
Shell.RegWrite Keys(i,1)&Keys(i,0),Keys(i,2),Keys(i,3)
End If
Next

Извлечение значение из параметра Windows, который находится в разделе HKLM\SOFTWARE\Microsoft\

Извлечение значение из параметра по умолчанию, который находится в разделе HKLM\SOFTWARE\Microsoft\Windows\

Также нужно учитывать, что если раздела не существует, как и его параметра по умолчанию, то будет выброшено исключение, которое нужно корректно обработать.

Суммировав все вышесказанное, мы получим достаточно простую функцию, листинг которой представлен далее.

Листинг 1 . Функция проверки существования раздела.

А чтобы картина была полной, ниже показана функция, с помощью которой проверяется существование параметра в реестре.

VBscript ,writing into registry

when i execute the code it always gave an error, ‘Invalid Root in Registry’ whats wrong with the code could somebody explain this ?

Sufiyan Ghori's user avatar

2 Answers 2

Try «HKEY_LOCAL_MACHINE» instead of HKLM. «HKEY_CURRENT_USER» instead of HKCU.

There are three arguments regarding registery write in vbs . For more information please head towards https://www.vbsedit.com/html/678e6992-ddc4-4333-a78c-6415c9ebcc77.asp

Problem is that you are not referring the size of registery i.e REG_SZ, DWORD , QWORD etc.

boga khan's user avatar

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.12.19.43125

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

VBS: Запуск REGEDIT.EXE на заданном разделе реестра

Если вспомнить, что regedit открывается всегда на том же ключе, на котором мы его спозиционировали в предыдущем сеансе работы, и найти ключик, в котором он сохраняет это местоположение, то задачу открытия regedit на любом заданном ключе можно очень сильно упростить.
Вся процедура открытия будет сводится к 2 этапам:
1. Загоняем в ключ HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit\Lastkey значение ветки, которую нам необходимо открыть.
2. Запускаем regedit.
Работает это исключительно быстро.

Однако, этот совет не сработает, если REGEDIT.EXE уже запущен (в том числе от имени другого пользователя). Поэтому, запускаем его с ключом /m:

Ключи и параметры запуска стандартных приложений

__________
Редактор реестра regedit.exe.
regedit.exe [параметр] [имя файла]

/m — Запускает новый экземпляр Редактора реестра в отдельном процессе (начиная с Windows XP и выше)

и эта казавшаяся вынужденной мера оказывается исключительным удобством, позволяющим, например, в двух окнах REGEDIT.EXE просматривать взаимосвязаные ProgId и ClassId или сравнивать одинаковые разделы реестра у разных пользователей.

Путь к открываемому разделу реестра можно передавать скрипту как аргумент командной строки или вводить в диалоговом окне InputBox(). Если путь начинается непосредственно с имени корневогого раздела реестра (без указания перед ним компьютера), то имя корневого раздела можно сокращать (HKCR, HKCU, HKLM, HKU, HKCC), но при этом обязательно после сокращенного имени ставить «\», даже если после него ничего больше не идёт.

Скрипт позволяет запускать редактор реестра от имени другого пользователя: для этого перед путём к разделу реестра надо поставить знак «+», после чего будет показан стандартный диалог запуска приложения от имени другого пользователя. Если после «+» не указать путь к разделу реестра, то скрипт просто будет перезапущен от имени другого пользователя (чтобы не заблудиться, имя пользователя показывается в заголовке окна).

Скрипт особенно удобно использовать, если создать на него ярлык и назначить ему сочетание клавиш по своему вкусу (например, Ctrl+Alt+R), сам ярлык можно запрятать в меню «Пуск» в папку второго-третьего уровня, чтобы не мешался перед глазами (можно для подобных ярлыков выделить отдельную папку).

Известная проблема: Из-за невозможности в WSH передачи кавычек в аргументах командной строки не получится в пакетном режиме или от имени другого пользователя открыть раздел, содержащий в пути кавычки, что, к счастью, встречается крайне нечасто.

Vbs как перейти к ключу в реестре

[HKEY_CURRENT_USER\Software\Mic rosoft\Windows\CurrentVersion\ Explorer\Shell Folders]
.
.
«Administrative Tools»=»C:\\Users\\Alexsandr\\AppDat a\\Roaming\\Microsoft\\Windows \\Start Menu\\Programs\\Administrative Tools»
«Personal»=»M:\\My Documents»
.
.
Заранее спасибо за ответ.

Чтение и запись данных в реестр
Программа при открытии должна обращаться к базе данных. Путь и файл получаю через диалоговое окно.

Запись в реестр
Ни как не создаётся параметр сключом в windows 8.1 в 7 было всё впорядке. HKEY_LOCAL_MACHINE не.

Похожие статьи