Checking existence of registry key value in for loop batch

4

I am writing a batch script to check if a registry key value exists and I am having some issues. When I directly specify a key to look for, the %ERRORLEVEL% updates appropriately. The example below echos the value 1 as expected.

REG QUERY HKLM /v NONEXISTENT_KEY
ECHO %ERRORLEVEL%

However I am checking the existence of a bunch of keys in a file so I am looping over it with FOR. The following echos 0 for some reason that I do not understand.

FOR /F "tokens=1-2 delims=," %%A IN (myFile.txt) DO (
    REG QUERY "%%A" /v "%%B"
    ECHO %ERRORLEVEL%

Note: the structure of the file I am looping over is demonstrated in the following example:

HKEY_LOCAL_MACHINE\PATH\TO\KEY,SOME VALUE

Alex

Posted 2017-08-09T14:43:31.647

Reputation: 143

Have you tried using Setlocal EnableDelayedExpansion together with ECHO !ERRORLEVEL!?

– DavidPostill – 2017-08-09T15:05:20.463

Just tried this, the error level is still returned as 0 despite the key value not existing. – Alex – 2017-08-09T15:10:54.740

EDIT Sorry I forgot to change my '%'s to '!'s. It works after doing that. – Alex – 2017-08-09T15:16:14.973

Yes, just confirmed by testing. Writing an answer. – DavidPostill – 2017-08-09T15:38:44.253

Answers

1

The following echos 0 for some reason that I do not understand.

FOR /F "tokens=1-2 delims=," %%A IN (myFile.txt) DO (
    REG QUERY "%%A" /v "%%B"
    ECHO %ERRORLEVEL%

You need to EnableDelayedExpansion together and use ECHO !ERRORLEVEL!.

Corrected batch file:

@echo off
setlocal enabledelayedexpansion
FOR /F "tokens=1-2 delims=," %%A IN (myFile.txt) DO (
    REG QUERY "%%A" /v "%%B"
    ECHO !ERRORLEVEL!
  )
endlocal

Output:

> type myFile.txt
HKEY_LOCAL_MACHINE\PATH\TO\KEY,SOME VALUE

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

Further Reading

DavidPostill

Posted 2017-08-09T14:43:31.647

Reputation: 118 938

What is the role of EnableDelayedExpansion? I can't understand from ss64, can you explain it? – Biswapriyo – 2017-08-10T04:09:59.590

@Biswa In a loop you must use delayed expansion to evaluate a variables value each time the loop is executed. Without delayed expansion it is evaluated only once when the batch file is parsed (that happens when it is read). – DavidPostill – 2017-08-10T09:30:06.913