- How to add, modify, or delete registry subkeys and values by using a .reg file
- IN THIS TASK
- Summary
- Registry Key Security and Access Rights
- Working with Registry Keys
- Listing All Subkeys of a Registry Key
- Copying Keys
- Creating Keys
- Deleting Keys
- Removing All Keys Under a Specific Key
- Registry Key Класс
- Определение
- Примеры
- Комментарии
- Свойства
- Методы
- Явные реализации интерфейса
- Методы расширения
How to add, modify, or delete registry subkeys and values by using a .reg file
This article is intended for advanced users, administrators, and IT Professionals.
Importing Registration Entries (.reg) files is a feature of Regedit.exe and is not supported by Regedt32.exe. You can use Regedit.exe to make some changes to the registry on a Windows NT 4.0-based or Windows 2000-based computer, but some changes require Regedt32.exe. For example, you cannot add or change REG_EXPAND_SZ or REG_MULTI_SZ values with Regedit.exe on a Windows NT 4.0-based or Windows 2000-based computer. Regedt32.exe is the primary Registry Editor for Windows NT 4.0 and Windows 2000. If you must use Regedt32.exe, you cannot use Registration Entries (.reg) files to modify the registry. For more information about the differences between Regedit.exe and Regedt32.exe, click the following article number to view the article in the Microsoft Knowledge Base:
141377 Differences between Regedit.exe and Regedt32.exe
IN THIS TASK
Summary
Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
322756 How to back up and restore the registry in Windows This step-by-step article describes how to add, modify, or delete registry subkeys and values by using a Registration Entries (.reg) file. Regedit.exe uses .reg files to import and export registry subkeys and values. You can use these .reg files to remotely distribute registry changes to several Windows-based computers. When you run a .reg file, the file contents merge into the local registry. Therefore, you must distribute .reg files with caution.
A .reg file has the following syntax:
RegistryEditorVersion
Blank line
[ RegistryPath1]
» DataItemName1«=» DataType1: DataValue1»
DataItemName2«=» DataType2: DataValue2»
Blank line
[ RegistryPath2]
» DataItemName3«=» DataType3: DataValue3«
RegistryEditorVersion is either «Windows Registry Editor Version 5.00» for Windows 2000, Windows XP, and Windows Server 2003, or «REGEDIT4» for Windows 98 and Windows NT 4.0. The «REGEDIT4» header also works on Windows 2000-based, Windows XP-based, and Windows Server 2003-based computers.
Blank line is a blank line. This identifies the start of a new registry path. Each key or subkey is a new registry path. If you have several keys in your .reg file, blank lines can help you to examine and to troubleshoot the contents.
RegistryPathx is the path of the subkey that holds the first value you are importing. Enclose the path in square brackets, and separate each level of the hierarchy by a backslash. For example:
[ HKEY_LOCAL_ MACHINE\SOFTWARE\Policies\Microsoft\Windows\System] A .reg file can contain several registry paths. If the bottom of the hierarchy in the path statement does not exist in the registry, a new subkey is created. The contents of the registry files are sent to the registry in the order you enter them. Therefore, if you want to create a new subkey with another subkey below it, you must enter the lines in the correct order.
DataItemNamex is the name of the data item that you want to import. If a data item in your file does not exist in the registry, the .reg file adds it (with the value of the data item). If a data item does exist, the value in your .reg file overwrites the existing value. Quotation marks enclose the name of the data item. An equal sign (=) immediately follows the name of the data item.
Registry Key Security and Access Rights
The Windows security model enables you to control access to registry keys. For more information about security, see Access-Control Model.
You can specify a security descriptor for a registry key when you call the RegCreateKeyEx or RegSetKeySecurity function. If you specify NULL, the key gets a default security descriptor. The ACLs in a default security descriptor for a key are inherited from its direct parent key.
The valid access rights for registry keys include the DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER standard access rights. Registry keys do not support the SYNCHRONIZE standard access right.
The following table lists the specific access rights for registry key objects.
Value | Meaning |
---|---|
KEY_ALL_ACCESS (0xF003F) | Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights. |
KEY_CREATE_LINK (0x0020) | Reserved for system use. |
KEY_CREATE_SUB_KEY (0x0004) | Required to create a subkey of a registry key. |
KEY_ENUMERATE_SUB_KEYS (0x0008) | Required to enumerate the subkeys of a registry key. |
KEY_EXECUTE (0x20019) | Equivalent to KEY_READ. |
KEY_NOTIFY (0x0010) | Required to request change notifications for a registry key or for subkeys of a registry key. |
KEY_QUERY_VALUE (0x0001) | Required to query the values of a registry key. |
KEY_READ (0x20019) | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values. |
KEY_SET_VALUE (0x0002) | Required to create, delete, or set a registry value. |
KEY_WOW64_32KEY (0x0200) | Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. This flag is ignored by 32-bit Windows. For more information, see Accessing an Alternate Registry View. This flag must be combined using the OR operator with the other flags in this table that either query or access registry values. Windows 2000: This flag is not supported. |
KEY_WOW64_64KEY (0x0100) | Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. This flag is ignored by 32-bit Windows. For more information, see Accessing an Alternate Registry View. This flag must be combined using the OR operator with the other flags in this table that either query or access registry values. Windows 2000: This flag is not supported. |
KEY_WRITE (0x20006) | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights. |
When you call the RegOpenKeyEx function, the system checks the requested access rights against the key’s security descriptor. If the user does not have the correct access to the registry key, the open operation fails. If an administrator needs access to the key, the solution is to enable the SE_TAKE_OWNERSHIP_NAME privilege and open the registry key with WRITE_OWNER access. For more information, see Enabling and Disabling Privileges.
You can request the ACCESS_SYSTEM_SECURITY access right to a registry key if you want to read or write the key’s system access control list (SACL). For more information, see Access-Control Lists (ACLs) and SACL Access Right.
To view the current access rights for a key, including the predefined keys, use the Registry Editor (Regedt32.exe). After navigating to the desired key, go to the Edit menu and select Permissions.
Working with Registry Keys
Because registry keys are items on PowerShell drives, working with them is very similar to working with files and folders. One critical difference is that every item on a registry-based PowerShell drive is a container, just like a folder on a file system drive. However, registry entries and their associated values are properties of the items, not distinct items.
Listing All Subkeys of a Registry Key
You can show all items directly within a registry key by using Get-ChildItem . Add the optional Force parameter to display hidden or system items. For example, this command displays the items directly within PowerShell drive HKCU: , which corresponds to the HKEY_CURRENT_USER registry hive:
These are the top-level keys visible under HKEY_CURRENT_USER in the Registry Editor (Regedit.exe).
You can also specify this registry path by specifying the registry provider’s name, followed by :: . The registry provider’s full name is Microsoft.PowerShell.Core\Registry , but this can be shortened to just Registry . Any of the following commands will list the contents directly under HKCU: .
These commands list only the directly contained items, much like using DIR in Cmd.exe or ls in a UNIX shell. To show contained items, you need to specify the Recurse parameter. To list all registry keys in HKCU: , use the following command.
Get-ChildItem can perform complex filtering capabilities through its Path, Filter, Include, and Exclude parameters, but those parameters are typically based only on name. You can perform complex filtering based on other properties of items by using the Where-Object cmdlet. The following command finds all keys within HKCU:\Software that have no more than one subkey and also have exactly four values:
Copying Keys
Copying is done with Copy-Item . The following example copies the CurrentVersion subkey of HKLM:\SOFTWARE\Microsoft\Windows\ and all of its properties to HKCU:\ .
If you examine this new key in the registry editor or by using Get-ChildItem , you notice that you do not have copies of the contained subkeys in the new location. In order to copy all of the contents of a container, you need to specify the Recurse parameter. To make the preceding copy command recursive, you would use this command:
You can still use other tools you already have available to perform filesystem copies. Any registry editing tools—including reg.exe, regini.exe, regedit.exe, and COM objects that support registry editing, such as WScript.Shell and WMI’s StdRegProv class can be used from within Windows PowerShell.
Creating Keys
Creating new keys in the registry is simpler than creating a new item in a file system. Because all registry keys are containers, you do not need to specify the item type; you simply supply an explicit path, such as:
You can also use a provider-based path to specify a key:
Deleting Keys
Deleting items is essentially the same for all providers. The following commands will silently remove items:
Removing All Keys Under a Specific Key
You can remove contained items by using Remove-Item , but you will be prompted to confirm the removal if the item contains anything else. For example, if we attempt to delete the HKCU:\CurrentVersion subkey we created, we see this:
To delete contained items without prompting, specify the Recurse parameter:
If you wanted to remove all items within HKCU:\CurrentVersion but not HKCU:\CurrentVersion itself, you could instead use:
Registry Key Класс
Определение
Представляет узел уровня раздела в реестре Windows. Represents a key-level node in the Windows registry. Этот класс является инкапсуляцией реестра. This class is a registry encapsulation.
Примеры
В следующем примере кода показано, как создать подраздел в разделе HKEY_CURRENT_USER, манипулировать его содержимым, а затем удалить подраздел. The following code example shows how to create a subkey under HKEY_CURRENT_USER, manipulate its contents, and then delete the subkey.
Комментарии
Чтобы получить экземпляр RegistryKey , используйте один из статических членов Registry класса. To get an instance of RegistryKey, use one of the static members of the Registry class.
Реестр выступает в качестве центрального репозитория данных для операционной системы и приложений на компьютере. The registry acts as a central repository of information for the operating system and the applications on a computer. Реестр организован в виде иерархического формата, основанного на логическом упорядочении элементов, хранящихся в нем (см Registry . раздел для элементов базового уровня в этой иерархии). The registry is organized in a hierarchical format, based on a logical ordering of the elements stored within it (please see Registry for the base-level items in this hierarchy). При хранении сведений в реестре выберите соответствующее расположение в зависимости от типа сохраняемых данных. When storing information in the registry, select the appropriate location based on the type of information being stored. Избегайте уничтожения данных, созданных другими приложениями, так как это может привести к непредвиденному поведению приложений, а также может оказать негативное воздействие на работу вашего приложения. Be sure to avoid destroying information created by other applications, because this can cause those applications to exhibit unexpected behavior, and can also have an adverse effect upon your own application.
Этот тип реализует интерфейс IDisposable. This type implements the IDisposable interface. По окончании использования выдаленную ему память следует прямо или косвенно освободить. When you have finished using the type, you should dispose of it either directly or indirectly. Чтобы сделать это прямо, вызовите его метод Dispose в блоке try / catch . To dispose of the type directly, call its Dispose method in a try / catch block. Чтобы сделать это косвенно, используйте языковые конструкции, такие как using (в C#) или Using (в Visual Basic). To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Дополнительные сведения см. в разделе «Использование объекта, реализующего IDisposable» в статье об интерфейсе IDisposable. For more information, see the «Using an Object that Implements IDisposable» section in the IDisposable interface topic.
Разделы реестра являются базовой единицей организации в реестре и могут сравниваться с папками в проводнике. Registry keys are the base unit of organization in the registry, and can be compared to folders in File Explorer. У конкретного ключа могут быть подразделы, так же как и папка, которая может содержать вложенные папки. A particular key can have subkeys, just as a folder can have subfolders. Каждый ключ можно удалить при условии, что у пользователя есть соответствующие разрешения, и ключ не является базовым ключом или на уровне, расположенном непосредственно под базовыми ключами. Each key can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key or at the level directly under the base keys. С каждым ключом также может быть связано несколько значений (значение может сравниваться с файлом), которое используется для хранения информации, например сведения о приложении, установленном на компьютере. Each key can also have multiple values associated with it (a value can be compared to a file), which are used to store the information — for example, information about an application installed on the computer. Каждое значение содержит один конкретный фрагмент информации, который может быть получен или обновлен при необходимости. Each value holds one particular piece of information, which can be retrieved or updated when required. Например, вы можете создать RegistryKey для своей компании в разделе HKEY_LOCAL_MACHINE\Software ключей, а затем подраздел для каждого приложения, создаваемого вашей компанией. For instance, you can create a RegistryKey for your company, under the key HKEY_LOCAL_MACHINE\Software, and then a subkey for each application that your company creates. Каждый подраздел содержит сведения, относящиеся к этому приложению, такие как параметры цвета, расположение и размер экрана, или распознаваемые расширения файлов. Each subkey holds the information specific to that application, such as color settings, screen location and size, or recognized file extensions.
Обратите внимание, что данные, хранящиеся в реестре, доступны другим приложениям и пользователям, поэтому их не следует использовать для хранения данных безопасности или важных сведений о приложениях. Note that information stored in the registry is available to other applications and users, and therefore should not be used to store security data or critical application information.
Не предоставляйте RegistryKey объекты таким образом, чтобы вредоносная программа могла создать тысячи бессмысленных подразделов или пар «ключ-значение». Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. Например, не разрешать вызывающим объектам вводить произвольные ключи или значения. For example, do not allow callers to enter arbitrary keys or values.
Начиная с платформа .NET Framework 4 Длина раздела реестра больше не ограничена 255 символами. Starting in the .NET Framework 4, the length of a registry key is no longer limited to 255 characters.
Свойства
Получает объект SafeRegistryHandle, представляющий раздел реестра, инкапсулируемый текущим объектом RegistryKey. Gets a SafeRegistryHandle object that represents the registry key that the current RegistryKey object encapsulates.
Возвращает имя раздела. Retrieves the name of the key.
Возвращает количество подразделов для текущего раздела. Retrieves the count of subkeys of the current key.
Возвращает число значений в разделе. Retrieves the count of values in the key.
Получает представление, которое использовалось для создания раздела реестра. Gets the view that was used to create the registry key.
Методы
Если содержимое раздела было изменено, следует закрыть раздел и записать его на диск. Closes the key and flushes it to disk if its contents have been modified.
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Создает новый вложенный раздел или открывает существующий вложенный раздел с доступом на запись. Creates a new subkey or opens an existing subkey for write access.
Создает новый подраздел или открывает существующий с указанным доступом. Creates a new subkey or opens an existing subkey with the specified access. Доступно начиная с .NET Framework 4.6. Available starting with .NET Framework 4.6.
Создает новый подраздел или открывает существующий с указанным доступом. Creates a new subkey or opens an existing subkey with the specified access. Доступно начиная с .NET Framework 4.6. Available starting with .NET Framework 4.6.
Создает новый вложенный раздел или открывает существующий вложенный раздел с доступом на запись, используя заданный вариант проверки разрешений. Creates a new subkey or opens an existing subkey for write access, using the specified permission check option.
Создает подраздел или открывает подраздел с доступом на запись, используя заданные параметры проверки разрешений и параметры реестра. Creates a subkey or opens a subkey for write access, using the specified permission check and registry options.
Создает подраздел или подраздел с доступом на запись, используя заданные параметры проверки разрешений, параметры реестра и безопасности реестра. Creates a subkey or opens a subkey for write access, using the specified permission check option, registry option, and registry security.
Создает новый вложенный раздел или открывает существующий вложенный раздел с доступом на запись, используя заданный вариант проверки разрешений и безопасности реестра. Creates a new subkey or opens an existing subkey for write access, using the specified permission check option and registry security.
Удаляет заданный подраздел. Deletes the specified subkey.
Удаляет указанный подраздел и определяет, нужно ли создавать исключение, если подраздел не найден. Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found.
Рекурсивно удаляет вложенный раздел и все дочерние вложенные разделы. Deletes a subkey and any child subkeys recursively.
Рекурсивно удаляет указанный подраздел и все дочерние подразделы и определяет, нужно ли создавать исключение, если не удается найти подраздел. Deletes the specified subkey and any child subkeys recursively, and specifies whether an exception is raised if the subkey is not found.
Удаляет заданное значение из этого раздела. Deletes the specified value from this key.
Удаляет указанное значение из данного раздела и определяет, нужно ли создавать исключение, если значение на найдено. Deletes the specified value from this key, and specifies whether an exception is raised if the value is not found.
Освобождает все ресурсы, используемые текущим экземпляром класса RegistryKey. Releases all resources used by the current instance of the RegistryKey class.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Если содержимое раздела было изменено, следует закрыть раздел и записать его на диск. Closes the key and flushes it to disk if the contents have been modified.
Записывает в реестр все атрибуты заданного открытого раздела реестра. Writes all the attributes of the specified open registry key into the registry.
Создает раздел реестра на базе указанного дескриптора. Creates a registry key from a specified handle.
Создает раздел реестра на базе указанного дескриптора и параметров представления реестра. Creates a registry key from a specified handle and registry view setting.
Возвращает безопасность элемента управления доступом для текущего раздела реестра. Returns the access control security for the current registry key.
Возвращает заданные разделы безопасности элемента управления доступом для текущего раздела реестра. Returns the specified sections of the access control security for the current registry key.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает массив строк, который содержит все имена подразделов. Retrieves an array of strings that contains all the subkey names.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Возвращает значение, связанное с заданным именем. Retrieves the value associated with the specified name. Возвращает null , если пара «имя-значение» отсутствует в реестре. Returns null if the name/value pair does not exist in the registry.
Возвращает значение, связанное с заданным именем. Retrieves the value associated with the specified name. Если имя не найдено, возвращает предоставленное значение по умолчанию. If the name is not found, returns the default value that you provide.
Возвращает значение, связанное с заданным именем и параметрами извлечения. Retrieves the value associated with the specified name and retrieval options. Если имя не найдено, возвращает предоставленное значение по умолчанию. If the name is not found, returns the default value that you provide.
Возвращает тип данных реестра для значения, связанного с заданным именем. Retrieves the registry data type of the value associated with the specified name.
Возвращает массив строк, содержащий все имена значений, связанных с этим разделом. Retrieves an array of strings that contains all the value names associated with this key.
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Открывает новый объект RegistryKey, который представляет запрошенный раздел на локальном компьютере в указанном представлении. Opens a new RegistryKey that represents the requested key on the local machine with the specified view.
Открытие нового раздела RegistryKey, который представляет запрошенный раздел на удаленном компьютере. Opens a new RegistryKey that represents the requested key on a remote machine.
Открывает новый раздел реестра, который представляет запрошенный раздел на удаленном компьютере в указанном представлении. Opens a new registry key that represents the requested key on a remote machine with the specified view.
Возвращает подраздел с доступом только для чтения. Retrieves a subkey as read-only.
Получает указанный подраздел и определяет, следует ли предоставить доступ для записи в этот раздел. Retrieves a specified subkey, and specifies whether write access is to be applied to the key.
Возвращает заданный подраздел с доступом для чтения или для чтения и записи. Retrieves the specified subkey for read or read/write access.
Возвращает заданный подраздел с доступом для чтения или для чтения и записи с запросом заданных прав доступа. Retrieves the specified subkey for read or read/write access, requesting the specified access rights.
Возвращает подраздел с указанным именем и правами доступа. Retrieves a subkey with the specified name and access rights. Доступно начиная с .NET Framework 4.6. Available starting with .NET Framework 4.6.
Применяет безопасность управления доступом Windows к существующему разделу реестра. Applies Windows access control security to an existing registry key.
Задает указанную пару «имя-значение». Sets the specified name/value pair.
Устанавливает значение пары «имя-значение» в разделе реестра, используя заданный тип данных реестра. Sets the value of a name/value pair in the registry key, using the specified registry data type.
Возвращает строковое представление этого раздела. Retrieves a string representation of this key.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Явные реализации интерфейса
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода.
Выполняет Close() в текущем реестре. Performs a Close() on the current key.
Методы расширения
Возвращает сведения безопасности для раздела реестра. Returns the security information of a registry key.
Возвращает сведения безопасности для раздела реестра. Returns the security information of a registry key.
Изменяет атрибуты безопасности для существующего раздела реестра. Changes the security attributes of an existing registry key.