如何从批处理脚本中获取注册表项的值? [英] How can I get the value of a registry key from within a batch script?

查看:31
本文介绍了如何从批处理脚本中获取注册表项的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用一个 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 来停止 stderr,但是如果我只调用命令,这会起作用:

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_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 是必需的,因为 REG QUERY 的命令使用双引号.

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

skip=4 忽略所有输出,除了具有值名称、类型和值的行(如果存在).

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

2^>nul 防止出现错误文本.^ 是转义字符,可让您将 > 放在 for 命令中.

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_USERSoftwareMicrosoftCommand Processor"BogusValue not found.

这篇关于如何从批处理脚本中获取注册表项的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆