Suppressing error in batch command if reg

1

If I run the following:

@ECHO OFF
FOR /F "tokens=2* delims=    " %%A IN ('REG QUERY "HKLM\SOFTWARE\SomeApp\Server" /v ServerName') DO SET ServerName=%%B
ECHO Server:  %ServerName%

and the registry doesn't exist, it gives the following error

ERROR: The system was unable to find the specified registry key or value.

I know the error is expected, but how can suppress this error?

Not too concerned about the ECHO part showing just "SERVER:" with no value, that's fine to me.

BondUniverse

Posted 2015-04-07T16:24:20.580

Reputation: 455

Answers

2

That message is coming because the REG command is writing to either the standard output stream or the standard error stream. If you really don't care about the messages, you can redirect that output so that it is not displayed.

Change your command to:

REG QUERY "HKLM\SOFTWARE\SomeApp\Server" /v ServerName > nul 2> nul

heavyd

Posted 2015-04-07T16:24:20.580

Reputation: 54 755

This answer is wrong. You need to escape redirect operator as mentioned in the other answer – Abhijit – 2016-05-26T09:22:27.040

4

FOR /F "tokens=2*" %%A IN ('
    REG QUERY "HKLM\SOFTWARE\SomeApp\Server" /v ServerName 2^> nul 
') DO SET "ServerName=%%B"

ECHO Server:  %ServerName%

Changes from your code:

  • (not needed) delims removed. Tabs and spaces are the default delimiters, there is no need to include them
  • (needed) The stderr stream (stream number 2) is redirected to nul device to hide the error output. The redirect operator > needs to be escaped when included inside the for /f command, from here the ^>
  • (recommended) set command is quoted to prevent problems with ending spaces or special characters in values. The quotes only protect the operation are not included in the value stored into the variable.

MC ND

Posted 2015-04-07T16:24:20.580

Reputation: 1 286