Read registry value that contains spaces using batch file

This problem happens because the string contains spaces and the second part of the string (possibly more parts if there are more spaces) are treated as another token (in 4, 5, etc.) To fix this, pass the rest of the line to %%C with an asterisk like this:

FOR /F "usebackq skip=2 tokens=1,2*" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set ValueName=%%A
    set ValueType=%%B
    set Home=%%C
)

The asterisk (*) means to pass the rest of the line into the next variable (with all the spaces).


@ECHO OFF
SETLOCAL
set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\My Entry"
set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Space Sciences Laboratory, U.C. Berkeley\BOINC Setup"
set VALUE_NAME=migrationdir

FOR /F "usebackq skip=2 tokens=1,2*" %%A IN (
 `REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    set "ValueName=%%A"
    set "ValueType=%%B"
    set Home="%%C"
)

IF DEFINED home SET home=%home:"=%
if defined Home echo Home = %Home%
if NOT defined Home echo %KEY_NAME%\%VALUE_NAME% not found.

Since I don't have ...\My Entry as a key, I've substituted a key I do have.

First item - since the data required contains a space, and space is a default delimiter, you need to use 1,2* as tokens - the first, second and remainder-of-line.

The next little difficulty is that the data item ALSO contain ) whic is interpreted as the closing parenthesis of the FOR/f hence giving an error - in your case, \Dir1\Dir2 not expected here

A way to overcome this is to quote, then strip the value assigned to home

But once again, the closing-parenthesis in home serves to terminate the TRUE portion of the IF statement.

switching on the presence/absence of a value assigned to HOME overcomes this. Obviously, the same could be said for Valuename although there's a hidden fail-to-fail here.

If the requested registry entry is not found, then the SETs in the FOR/f are not performed, hence the values of the three variables are not changed from any value they may have before the FOR/f is executed. Therefore, if home (or valuename if you choose to use that value) has a value of someexistingvalue before the for/f then unexpected results may be presented.

(BTW - it's legitimate and neater-looking to break the for/f at either or both of the parentheses of the IN clause)