Checking existence of registry key value in for loop batch

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

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

  • An A-Z Index of the Windows CMD command line
  • A categorized list of Windows CMD commands
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.