Обновлено:
Опубликовано:
Что такое реестр Windows простыми словами.
Большинство команд лучше выполнять, запустив командную строку от имени администратора. Для этого найдите ее по ключу cmd — кликните по файлу правой кнопкой мыши — выберите Запустить от имени администратора. Или в Windows 10 правой кнопкой по Пуск — Командная строка (администратор).
Чтение данных
Добавление параметров
Удаление
Редактирование
Импорт
Описание всех команд
Выборка (query)
reg query HKLM\Software\Microsoft
* в данном примере будет выведен на экран список веток, которые находятся в HKLM\Software\Microsoft
Если в пути встречается пробел, необходимо весь путь поместить в кавычки, например:
reg query «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings»
Чтобы вывести все вложенные ветки, запускаем команду с параметром /s:
reg query «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /s
Добавление (add)
Синтаксис:
reg add <Ключ> /v <Параметр> /t <Тип> /d <Значение>
Например, добавим настройки использования прокси-сервера для браузера Internet Explorer:
reg add «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /v ProxyEnable /t REG_DWORD /d 1
reg add «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /v ProxyServer /t REG_SZ /d «192.168.0.15:3128»
reg add «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /v ProxyOverride /t REG_SZ /d «<local>»
* где первая команда включает использование прокси-сервера; вторая прописывает использовать прокси с IP-адресом 192.168.0.15 и портом 3128; третья указывает не использовать прокси для локальных адресов.
Удаление (delete)
Синтаксис:
reg delete <Ключ> /v <Параметр>
Например, чтобы удалить одну из ранее созданной настройки, вводим следующую команду:
reg delete «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /v ProxyEnable /f
Чтобы удалить всю ветку с ее параметрами и значениями, вводим такую команду:
reg delete «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /va /f
Редактирование
Для редактирования значения нужно выполнить команду на добавление. Если ключ уже существует, команда заменить значение на новое:
reg add «HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings» /v ProxyEnable /t REG_DWORD /d 0 /f
* в данном примере будет изменено значение ключа ProxyEnable на 0 (или создан с таким значением); ключ f указывает на замену значения без вывода подтверждения.
Импорт
Во многих случаях проще выполнить импорт из файла, кликнув по нему дважды. Но, иногда необходимо выполнить импорт из командной строки:
reg import <путь к файлу>
Например:
reg import C:\Temp\import_proxy_settings.reg
* в данном примере мы импортировали настройки из файла import_proxy_settings.reg, который находится в каталоге C:\Temp\.
Краткое описание всех операций
В данной таблице приведены все возможные операции над коандой REG.
Операция | Описание |
---|---|
REG QUERY | Делает выборку ключей, параметров и значений |
REG ADD | Добавляет новую запись (параметр, ключ, значение) |
REG DELETE | Удаляет одну или несколько записей |
REG COPY | Копирует данные из одной ветки в другую |
REG SAVE | Сохраняет ветку со всеми параметрами и значениями в файл |
REG RESTORE | Восстанавливает ветку и данные из файла |
REG LOAD | Загружает данные в указанную ветку |
REG UNLOAD | Выгружает данные из указанной ветки |
REG COMPARE | Сравнивает две ветки |
REG EXPORT | Экспортирует все подразделы и параметры в файл .reg |
REG IMPORT | Импортирует все подразделы и параметры из файла .reg |
REG FLAGS | Показывает и устанавливает флаги для ветки |
Подробное описание всех ключей можно увидеть, введя команду reg <операция> /?
Например: reg add /?
The registry is the place where most of the applications store the settings but not only. Used also from the windows system to store important settings in order to be available to operate. We will cover a series of articles to explain how can be added, edited, and deleted the registry keys and values. This will be done using the Windows command prompt but not only. Will try to use also the PowerShell and GPO. In the end, you will be available to change them individually or over the network using batch. In this part, we will cover how to add registry key and values with command line, PowerShell, and batch file.
Check Also:
How to Edit Registry Key/value
How to Delete Registry Key/value
How to add registry key and value with CMD:
Below is the default commands line to add new registry key and “NewTestKey” on path “HKEY_CURRENT_USER\Software\” – To run it:
- Start
- Search “CMD”
- Run as Administrator
- Execute Below Command
reg add HKEY_CURRENT_USER\Software\NewTestKey
Add Registry Key CMD
Below is the default command to add new registry value entry “TestValue” of type “DWORD (32-bit)” on path “HKEY_CURRENT_USER\Software\NewTestKey\” and add the value of “1”. To run it:
- Start
- Search “CMD”
- Run as Administrator
- Execute Below Command
Customized:
reg add HKEY_CURRENT_USER\Software\NewTestKey\ /v TestValue /t REG_DWORD /d 1
Default Command:
Reg Add Regkey /v RegValue /t RegType /d data
Command Description:
- Regkey – Path where the new value should be added.
- RegValue – Name of the value that should be added
- /t – Type of the value (REG_SZ, REG_DWORD, REG_BINARY)
- /d Data – Specifies the data for the new entry in the registry.
Add Registry Value CMD
How to add Registry key and value with PowerShell:
Below is the PowerShell default command to add new registry key “NewTestKey” on path “HKEY_CURRENT_USER\Software\” – To run it:
- Start
- Search PowerShell
- Run as Administrator
- Execute Below Command
# Set the location to the registry Set-Location -Path 'HKCU:\Software\' # Create a new Key Get-Item -Path 'HKCU:\Software\' | New-Item -Name 'NewTestKey' –Force
Add Registry Key Powershell
Below is the PowerShell default command to add new registry value entry “TestValue” of type “DWORD (32-bit)” on the path “HKEY_CURRENT_USER\Software\NewTestKey\” and add the value of “1” – To run it:
- Start
- Search PowerShell
- Run as Administrator
- Execute Below Command
# Create new items with values New-ItemProperty -Path 'HKCU:\Software\NewTestKey' -Name 'TestValue' -Value '1' -PropertyType 'DWORD' –Force # Get out of the Registry Pop-Location
Add Registry Value PowerShell
How to add Registry key and value on a remote computer:
Below is the command to add registry key on a remote computer. To run it:
- Start
- Search “CMD”
- Run as Administrator
- Execute Below Command
REG ADD \\ComputerName\HKCU\Software\NewTestKey
Below is the command to add registry value on a remote computer. To run it:
- Start
- Search “CMD”
- Run as Administrator
- Execute Below Command
REG ADD \\ComputerName\HKCU\Software\NewTestKey /v TestValue /t REG_DWORD /d 1
How to add registry key and value with batch file:
The same commands used above to add the registry key from the command prompt can be integrated on the batch file. The commands can be used on the existing batch along with other commands or on the new batch file. To create a new batch file:
- Open a notepad files
- Write the below command
@echo off reg add HKEY_CURRENT_USER\Software\NewTestKey reg add HKEY_CURRENT_USER\Software\NewTestKey\ /v TestValue /t REG_DWORD /d 1
- Save it as regedit.bat
- Run it with DoubleClick and the command will be executed.
The bat files used mostly when you want to spread it over the network using GPO or SCCM
How to add registry key and value with regedit file (.reg)
You can add registry key and value by using .reg file. This file structure can be found by exporting certain keys from the regedit interface by right-clicking on it and the export option. To create it from the screech:
- Open a notepad file
- Copy and paste the below command
Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Software\NewTestKey2]
- Save it at addkey.reg
This command with creates NewTestKey2 key if does not exist. To add registry value copy and paste the following command:
Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Software\NewTestKey2] @="HKEY_CURRENT_USER\\Software" "TestValue"=dword:00000001
The command with creating new value “TestValue” of type dword with value “1”. To execute .reg files, double-click it and after typing to the confirmation yes the changes with be done.
Add Registry Key with regedit
Conclusion:
Those are the methods to add registry key and values using command prompt, PowerShell, and batch files. Follow us for the next articles where we will explain the methods to edit and delete keys and values from the registry
The `reg add` command is used to create or modify registry keys and values in the Windows Registry from the command line.
reg add "HKCU\Software\MyApp" /v "MyValue" /t REG_SZ /d "MyData" /f
Understanding the Windows Registry
What is the Windows Registry?
The Windows Registry is a crucial component of the Windows operating system, acting as a centralized database that stores configuration settings and options for the operating system and installed applications. It contains information, settings, and options for both the operating system and applications, making it foundational for system operation and performance.
Key Components of the Registry
The Registry is organized into a hierarchical structure, consisting of various hives, keys, and values. Here’s a closer look:
-
Hives: The primary divisions of the Registry, each storing data related to different aspects of the system. Major hives include:
- HKEY_LOCAL_MACHINE (HKLM): Contains settings and configuration for the local machine.
- HKEY_CURRENT_USER (HKCU): Stores user-specific settings.
-
Keys and Values: Each hive contains keys (which can be thought of as folders) that in turn contain values (which hold specific data). Each value may have different types, such as strings, DWORDs, or binary data.
Using Rem in Cmd: A Quick Guide to Comments
What is the `reg add` Command?
Purpose of the `reg add` Command
The `reg add` command is part of the Command Prompt in Windows and is used to create new registry keys or modify the values of existing keys. This command is particularly useful for system administrators and advanced users who want to automate system configuration or make bulk changes to the Registry.
Syntax of the `reg add` Command
The syntax for using the `reg add` command is as follows:
reg add [RootKey\][SubKey] [/v ValueName | /ve | /t Type | /s Separator | /d Data | /f]
Understanding this syntax is critical as it helps you understand the meaning of various arguments:
- RootKey: The main hive you are accessing (e.g., HKEY_CURRENT_USER).
- SubKey: The path to the key you want to access or create.
- /v ValueName: The name of the value to add.
- /ve: Option to specify the default value.
- /t Type: Specifies the data type (e.g., REG_SZ, REG_DWORD).
- /d Data: The actual data to set for the value.
- /f: Forces the operation without prompting for confirmation.
Mastering Arp A Cmd: Quick Guide to Network Mapping
Common Use Cases for `reg add`
Adding New Registry Keys
You may need to create new registry keys for various purposes, such as configuring software settings. For example, if you want to create a new setup for an application, you can use:
reg add HKEY_CURRENT_USER\Software\MyApp /v SettingName /d SettingValue /f
In this command:
- HKEY_CURRENT_USER\Software\MyApp is the path where the key will be created.
- /v SettingName indicates the name of the value.
- /d SettingValue specifies the data you’re assigning to that value.
- The /f flag commits the change without asking for confirmation.
Modifying Existing Registry Values
Sometimes, you will want to update the value of an existing key rather than create a new one. This can be achieved with a command like:
reg add HKEY_CURRENT_USER\Software\MyApp /v SettingName /d NewValue /f
This command modifies SettingName within HKEY_CURRENT_USER\Software\MyApp, changing its current value to NewValue.
Creating String and DWORD Values
You can also specify the type of value you wish to create. Here’s how you can add a string and a DWORD value:
- Example of Adding a String Value:
reg add HKEY_LOCAL_MACHINE\SOFTWARE\MyStringValue /ve /d "MyString" /f
Here, /ve specifies that you are adding a value for the default string.
- Example of Adding a DWORD Value:
reg add HKEY_CURRENT_USER\Software\MyDwordValue /v MyDWord /t REG_DWORD /d 1 /f
In this case, /t REG_DWORD tells the command that you are creating a DWORD value.
Mastering Grep in Cmd: A Quick Guide
Important Flags and Options
Detailed Explanation of Common Flags
When working with the `reg add` command, understanding the flags can significantly enhance your effectiveness:
- /v: This parameter defines the name of the value to be created or changed.
- /ve: Use this to define the default value of a key.
- /t: This flag specifies the type of data being supplied (e.g., REG_SZ for strings, REG_DWORD for DWORD numbers).
- /d: The data parameter is where you input the value you want to set.
- /f: This option forces the command to execute without a confirmation prompt, making it convenient for scripting or batch processes.
Create Cmd Shortcut: A Step-by-Step Guide
Best Practices for Using `reg add`
Backup Your Registry
Before making any changes to the Registry, it’s paramount to create a backup. This can save you from potential issues later if something goes wrong during the editing process. You can back up the Registry through the following:
reg export HKEY_CURRENT_USER\Software\MyApp Backup.reg
This command creates a backup file named Backup.reg, allowing you to restore settings if needed.
Testing Changes
Always test changes in a controlled environment, especially if you’re working in a production setting. By using virtual machines or secondary systems, you can ensure that your changes do not adversely affect user experience or system performance.
Understanding Permissions
Running the Command Prompt with administrator privileges is critical for making changes to certain sections of the Registry. Be aware of User Account Control (UAC), as it may prevent you from making changes without the necessary rights. Right-click on CMD and select Run as administrator before executing your commands.
Firewall Cmd Reload: A Simple Guide to Refreshing Security
Common Errors and Troubleshooting
Identifying Common Issues
Even experienced users can encounter issues when using the `reg add` command. Common errors may include:
- Syntax errors due to incorrect command structure.
- Permission issues if you lack administrative rights.
Troubleshooting Tips
To diagnose problems effectively, utilize the `reg query` command to verify the current settings:
reg query HKEY_CURRENT_USER\Software\MyApp
This command retrieves values in the specified location, allowing you to confirm whether your changes were successful.
Use system logs to help pinpoint errors or issues when executing your commands.
Mastering Firewall Cmd List: Essential Commands Simplified
Conclusion
The `reg add` command is a powerful tool that allows you to interact with the Windows Registry effectively. Whether you’re adding new keys or modifying existing values, understanding its operation equips you to automate configurations and enhance system performance safely. Approach with care, ensuring that you back up and test any changes before applying them broadly.
Trace Cmd: A Quick Guide to Command-Line Tracing
Additional Resources
For further learning and more nuanced approaches to using the Windows Registry, refer to the official Microsoft documentation and community forums, where experienced users share their solutions and best practices.
Prank Cmd: Fun Commands to Play on Friends
FAQs
Frequently Asked Questions About `reg add`
- Can I undo a `reg add` operation? While direct undo options do not exist, restoring your Registry from a backup will revert any changes made.
- Are there alternatives to using the Command Prompt for editing the Registry? Yes, the Registry Editor (regedit) provides a graphical interface for performing similar tasks with more visual feedback.
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
CQRS (Command Query Responsibility Segregation) на Java
Javaican 12.05.2025
CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .
Шаблоны и приёмы реализации DDD на C#
stackOverflow 12.05.2025
Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .
Исследование рантаймов контейнеров Docker, containerd и rkt
Mr. Docker 11.05.2025
Когда мы говорим о контейнерных рантаймах, мы обсуждаем программные компоненты, отвечающие за исполнение контейнеризованных приложений. Это тот слой, который берет образ контейнера и превращает его в. . .
Micronaut и GraalVM — будущее микросервисов на Java?
Javaican 11.05.2025
Облачные вычисления безжалостно обнажили ахиллесову пяту Java — прожорливость к ресурсам и медлительный старт приложений. Традиционные фреймворки, годами радовавшие корпоративных разработчиков своей. . .
on October 2, 2011
Using reg command we can add registry key from command line. Below you can find some examples for the same.
Add a new registry value:
The command for adding new registry value is given below.
Reg Add Regkey /v RegValue /t RegType /d data
Regkey – Path of the node where the new registry value should be added.
RegValue : Name of the registry value that should be added
/t: Type of the registry value (REG_SZ, REG_DWORD, REG_BINARY)
Example:
Add a new registry value ‘userpath’ of type REG_EXPAND_SZ under the node ‘HKEY_CURRENT_USER\Environment’. Assign the value ‘C:\Windows’ to this new registry value.
reg add HKEY_CURRENT_USER\Environment /v userpath /t REG_EXPAND_SZ /d C:\Windows
Add a new registry key
The command for adding new registry key is given below.
Reg Add Regkey
Example:
Add a new registry key ‘HKEY_CURRENT_USER\Software\Newregkey’.
reg add HKEY_CURRENT_USER\Software\Newregkey
Related Posts:
Delete registry key from Windows command prompt