Read and write REG_DWORD from batch file

2020-05-08 06:55发布

My requirement is to read a REG_DWORD from the registry and write it to another location. I have succeeded in reading from a registry location, but don't know how to write.

My code:

@echo off
REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\NetCache /v "OfflineDirRenameDelete"
SET previous=OfflineDirRenameDelete
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MySoftware /v "CacheDelete" /t REG_DWORD /d previous /f

This code fails, as "reg add" doesn't understand the "previous" variable

I am able to hard-code a value and set it to the registry. For example, this works:

REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MySoftware /v "CacheDelete" /t REG_DWORD /d 5454 /f

But I basically don't know how to dynamic REG_DWORD value to the registry.

标签: batch-file
2条回答
聊天终结者
2楼-- · 2020-05-08 07:46

The problem was that the REG QUERY instruction was returning something the name of the registry key, the type of it, and the value together. For example, it would be something like:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\CacheDelete
    LogLevel    REG_DWORD    0x29

And I was trying to set this value to another REG_DWORD in the registry, which obviously failed since this is more than a DWORD. And I may have had some syntax error and stuff in trying that too, so there's no wonder it failed.

The following code worked for me:

    @ECHO OFF

set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\NetCache"
set VALUE_NAME="OfflineDirRenameDelete"

FOR /F "usebackq skip=2 tokens=1,2*" %%A IN (
 `REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set "ValueName=%%A"
    set "ValueType=%%B"
    set Val="%%C"
)

reg add %KEY_NAME% /v "CacheDelete" /t REG_DWORD /d %Val% /f

Hope this helps someone!

查看更多
Explosion°爆炸
3楼-- · 2020-05-08 07:48

Use %previous% to get the content of the variable.

REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MySoftware /v "CacheDelete" /t REG_DWORD /d %previous% /f

Here is a quick reference on using variables in batch files.

查看更多
登录 后发表回答