tags:

views:

960

answers:

3

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.

A: 

The /F switch needs command extensions to be turned on. Usually they are turned on by default, but I'd check that. On XP systems you can turn them on doing something like

cmd /e:on

or checking the registry under

HKCU\Software\Microsoft\Command Processor\EnableExtensions

Dunno about Windows Server.

Doing help for and help cmd could provide some hints as well.

agnul
I did verify that EnableExtensions was set. I'll edit the question to note that.
Tim Danner
+1  A: 

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.

Mark Allen
+1  A: 

Wow, that is odd.

If the same commands work when split into two lines, then I'd guess it has something to do with the way the command gets run in a subshell in the FOR command.

If you were really dying to figure out why it's dying in this particular case, you could run commands like "SET > envvars.txt" as the FOR command and compare that with the top shell.

Or maybe start off simple and try running the REG command via CMD /C to see if that does anything?

One quick guess here, what's the values of COMSPEC and SHELL ?

Eric Tuttleman