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
  • Have you tried using Setlocal EnableDelayedExpansion together with ECHO !ERRORLEVEL!? – DavidPostill Aug 9 '17 at 15:05
  • Just tried this, the error level is still returned as 0 despite the key value not existing. – Alex Aug 9 '17 at 15:10
  • EDIT Sorry I forgot to change my '%'s to '!'s. It works after doing that. – Alex Aug 9 '17 at 15:16
  • Yes, just confirmed by testing. Writing an answer. – DavidPostill Aug 9 '17 at 15:38
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

| improve this answer | |
  • What is the role of EnableDelayedExpansion? I can't understand from ss64, can you explain it? – Biswapriyo Aug 10 '17 at 4:09
  • @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 Aug 10 '17 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.