Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

How can I get the value of a registry key from within a batch script?

I need to use a REG QUERY command to view the value of a key and set the result into a variable with this command:

FOR /F "tokens=2* delims=    " %%A IN ('REG QUERY "KeyName" /v ValueName') DO SET Variable=%%B

But if the key doesnt exists i get an error shown in the console. I need to hide this error! I tried putting a 2>nul after the command to stop the stderr, but this works if i only call the command:

REG QUERY "KeyName" /v ValueName 2>nul

If i put it into the FOR command like this:

FOR /F "tokens=2* delims=    " %%A IN ('REG QUERY "KeyName" /v ValueName') DO SET Variable=%%B 2>nul

The error is shown. So does anyone know how to hide the error? Or maybe another command too see if a key exists or not?

Thanks

PS: I'm using Windows XP

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works for me:

@echo OFF

setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor"
set VALUE_NAME=DefaultColor

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

if defined ValueName (
    @echo Value Name = %ValueName%
    @echo Value Type = %ValueType%
    @echo Value Value = %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
)

usebackq is needed since the command to REG QUERY uses double quotes.

skip=4 ignores all the output except for the line that has the value name, type and value, if it exists.

2^>nul prevents the error text from appearing. ^ is the escape character that lets you put the > in the for command.

When I run the script above as given, I get this output:

Value Name = DefaultColor
Value Type = REG_DWORD
Value Value = 0x0

If I change the value of VALUE_NAME to BogusValue then I get this:

"HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor"BogusValue not found.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...