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
精彩评论