Reputation: 77
I have a specific requirement to write a single command to check the registry value and process accordingly.
The command which i have used is:
reg query "HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" /v MSSQLSERVER > nul & if %ERRORLEVEL% NEQ 0 (echo "SQL Not Installed") else (echo "SQL Installed")
First time, since the errorlevel value is 0
, it shows
SQL Installed
even if SQL Not installed and from next continuous run onwards it shows as:
SQL Not Installed
What is the issue with the cmd.
Upvotes: 0
Views: 380
Reputation: 41244
if ERRORLEVEL 1
should work:
reg query "HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" /v MSSQLSERVER > nul & if ERRORLEVEL 1 (echo "SQL Not Installed") else (echo "SQL Installed")
Upvotes: 0
Reputation: 70933
The "problem" with your code is that when the parser reach that line, the %errorlevel%
variable is replaced with its value, and then the line is executed. So, any change to the value of the variable is not seen. The "usual" way of handling this cases is enabling delayed expansion and change the %errorlevel%
sintax with !errorlevel!
to indicate the parser that the value will change and need to be retrieved at execution time.
But, in this case, as you have the requirement of a "one liner", change the if
test to
if errorlevel 1 (echo "SQL Not Installed") else (echo "SQL Installed")
A standard construct to check for errorlevel without reading the variable value.
You have also the posibility to code it as
reg query .... && echo Installed || echo Not Installed
This executes the reg
command (with all your parameters, of course). On success, the command after &&
is executed. On failure the command after ||
is executed.
Upvotes: 2