Windows批处理:reg查询变量的键值,但如果键不存在则不显示错误(Windows Batch: reg query key value to a variable but do not disp

编程入门 行业动态 更新时间:2024-10-15 10:12:35
Windows批处理:reg查询变量的键值,但如果键不存在则不显示错误(Windows Batch: reg query key value to a variable but do not display error if key doesn't exist)

我有以下批处理命令,它获取一个注册表项并为变量赋值,但是当该键不存在时它会显示错误

for /f "tokens=2,*" %%a in ('reg query HKLM\Software\MySoftware\1.0\MyExecutable /v "InstallDir" ^| findstr InstallDir') do set InstallPath=%%b

有没有办法绕过异常? 我已经尝试在reg查询之后或在命令结束时使用2> NUL但是我得到一个异常2>此时是意外的。

非常感谢帮助/指导

I have the following batch command that fetches a registry key and assigns value to a variable but it displays error when the key doesn't exist

for /f "tokens=2,*" %%a in ('reg query HKLM\Software\MySoftware\1.0\MyExecutable /v "InstallDir" ^| findstr InstallDir') do set InstallPath=%%b

Is there a way to bypass the exception? I have tried using 2>NUL after the reg query or at the end of the command but I get an exception 2> was unexpected at this time.

help/ guidance much appreciated

最满意答案

您应该像管道一样解决问题。 ^| 简单地逃到2^>NUL

所以你得到了

for /f "tokens=2,*" %%a in ('reg query HKLM\Software\MySoftware\1.0\MyExecutable /v "InstallDir" 2^>NUL ^| findstr InstallDir') do set InstallPath=%%b

这是必要的,因为FOR-Loop的命令部分将被解析两次。 首先在批处理文件的上下文中(2> NUL是意外的),第二次在新的cmd.exe上下文中(那里2> NUL重定向reg命令的stderr)

You should solve the problem like with the pipe. ^| Simply escape it to 2^>NUL

So you get

for /f "tokens=2,*" %%a in ('reg query HKLM\Software\MySoftware\1.0\MyExecutable /v "InstallDir" 2^>NUL ^| findstr InstallDir') do set InstallPath=%%b

It's neccessary because the command part of the FOR-Loop will be parsed two times. First in the context of your batch file (there the 2>NUL is unexpected), and the second time in the new cmd.exe context (there the 2>NUL redirects the stderr of your reg command)

更多推荐

本文发布于:2023-08-03 07:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385445.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:批处理   不存在   变量   键值   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!