How to read a REG Value into an Environment Variab

2019-04-10 03:38发布

问题:

I am trying to read a REG Value into an Environment Variable in a BAT file. E.g.,

REG HKLM\SYSTEM\CurrentControlSet\Services\Eventlog /v ImagePath

I can get the entire output string of the REG command into an environment variable like this:

FOR /F "usebackq delims==" %%a in (`REG QUERY "HKLM\SYSTEM\CurrentControlSet\Services\Eventlog" /v ImagePath`) DO set ImagePath=%%a

However, this sets the environment variable to the entire line, i.e.,

ImagePath   REG_EXPAND_SZ   C:\Windows\system32\services.exe

I want the Environment Variable to consist only of the path portion, i.e.,

C:\Windows\system32\services.exe

Thanks for any tips.

回答1:

for /f "tokens=2*" %%A in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Services\Eventlog" /v ImagePath') DO set ImagePath=%%B

The default delimiter is space and tab; no need to change it. TOKENS=2* stores the 2nd token in %%A and the remainder of the line in %%B.

Concerning your original code - there is no benefit to using USEBACKQ in your situation. Also, your code would not preserve the entire line if it contained = because you used that as the delimiter.

Answer to comment
If you can rely on the fact that the path does not contain any spaces, then you can simply use "TOKENS=3" and save %%A. But I wouldn't trust that. Instead, I would use

for /f "tokens=2*" %%A in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Services\Eventlog" /v ImagePath') DO (
  for %%F in (%%B) do (
    set ImagePath=%%F
    goto :break
  )
)
:break