开发者

Windows Batch: reg query key value to a variable but do not display error if key doesn't exist

开发者 https://www.devze.com 2023-02-18 04:00 出处:网络
I have the following batch command that fetches a registry key and assigns value to a variable but it d开发者_如何学编程isplays error when the key doesn\'t exist

I have the following batch command that fetches a registry key and assigns value to a variable but it d开发者_如何学编程isplays 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


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)


Where after the reg query did you put it? This should work (look just before the findstr):

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

精彩评论

暂无评论...
验证码 换一张
取 消