我怎样才能从批处理脚本中获得一个注册表项的值? [英] How can I get the value of a registry key from within a batch script?
问题描述
我需要使用一个REG QUERY命令查看键的值,并将结果设置为使用此命令的变量:
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
但是,如果关键的犯规存在,我得到控制台中显示一个错误。我需要隐藏此错误!我试图把一个2> NUL命令后停止标准错误,但这个工作,如果我只调用命令:
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
如果我把它改成FOR命令是这样的:
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?
感谢
PS:我使用Windows XP
PS: I'm using Windows XP
推荐答案
这对我的作品:
@echo OFF
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_CURRENT_USER\Software\Microsoft\Command 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
因为该命令是需要 REG QUERY
使用双引号。
usebackq
is needed since the command to REG QUERY
uses double quotes.
跳过= 4
忽略所有的输出,除了具有值的名称,类型和值,该行如果它存在。
skip=4
ignores all the output except for the line that has the value name, type and value, if it exists.
2 ^> NUL
prevents出现错误文本。 ^
是转义字符,可以让你把>
在为
命令。
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
如果我更改 VALUE_NAME
的值 BogusValue
然后我得到这样的:
If I change the value of VALUE_NAME
to BogusValue
then I get this:
"HKEY_CURRENT_USER\Software\Microsoft\Command Processor"\BogusValue not found.
这篇关于我怎样才能从批处理脚本中获得一个注册表项的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!