Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does batch file FOR fail when iterating over command output?

I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:

FOR /F "tokens=2* delims=  " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B

(There's a tab character after delims=)

This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),
it fails with 'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName' is not recognized as an internal or external command, operable program or batch file.' Running the "reg query" command alone works fine. Reg.exe is present in C:\Windows\System32.

I was able to work around the problem by changing the code to

REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims=  " %%A IN (temp.txt) DO SET MyVariable=%%B

This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.

Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.

like image 377
Tim Danner Avatar asked Oct 08 '08 15:10

Tim Danner


1 Answers

I would check:

  1. The customer's role on the machine - are they an admin?
  2. Where is reg.exe on the box - is there more than one copy of copy of reg.exe in the path?
  3. Is there any locale difference on the customer's machine from the machines where this normally works?

Basically, enumerate everything that differs between this machine and machines where it works as expected. Include service packs, domain membership, etc.

like image 82
Mark Allen Avatar answered Oct 06 '22 21:10

Mark Allen