I need to use a REG QUERY command to view the value of a key and set the result into a variable with this command:
FOR /F \"tokens=2* delims= \" %%A IN (\
This work for me with variable that contains spaces on Windows 7:
FOR /F "usebackq tokens=3*" %%A IN (`REG QUERY "HKEY_LOCAL_MACHINE\Software\SomeAPP" /v ValueName`) DO (
set appdir=%%A %%B
)
ECHO %appdir%
Variable A
contains all data before first space, B
- rest part of ValueName (including further spaces), so appdir = ValueName
This works if the value contains a space:
FOR /F "skip=2 tokens=1,2*" %%A IN ('REG QUERY "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul') DO (
set ValueName=%%A
set ValueType=%%B
set ValueValue=%%C
)
if defined ValueName (
echo Value Name = %ValueName%
echo Value Type = %ValueType%
echo Value Value = %ValueValue%
) else (
@echo "%KEY_NAME%"\"%VALUE_NAME%" not found.
)
I've come across many errors on Windows XP computers when using WMIC (eg due to corrupted files on machines). Hence imo best not to use WMIC for Win XP in code. No problems with WMIC on Win 7 though.
You can get the value of a registry key as follows
@echo OFF
setlocal ENABLEEXTENSIONS
set REG_NAME="HKEY_CURRENT_USER\Software\Test"
set KEY_NAME=TestVal
FOR /F "usebackq skip=2 tokens=1-3" %%A IN (`REG QUERY %REG_NAME% /v %KEY_NAME% 2^>nul`) DO (
@echo %%A : %%C
)
pause
those who wonder how to add reg keys, here is a way.
REGEDIT4
; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT
[HKEY_CURRENT_USER\Software\Test]
"TestVal"="Succeeded"
echo Off
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup"
set VALUE_NAME=release
REG QUERY %KEY_NAME% /S /v %VALUE_NAME%
endlocal
dot put \ at the end of KEY_NAME
For some reason Patrick Cuff's code doesn't work on my system (Windows 7) probably due to tryingToBeClever's comment. Modifying it a little did the trick:
@echo OFF
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKEY_CURRENT_USER\Software\Microsoft\Command Processor
set VALUE_NAME=DefaultColor
FOR /F "tokens=1-3" %%A IN ('REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul') DO (
set ValueName=%%A
set ValueType=%%B
set ValueValue=%%C
)
if defined ValueName (
@echo Value Name = %ValueName%
@echo Value Type = %ValueType%
@echo Value Value = %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found.
)