How to get a registry value and set into a variable in batch

I need to get a value in a registry key and store in a variable using a batch file.

I wrote a basic command line to exemplify my logic (using echo instead of setting a variable):

for /f "tokens=3 delims=    " %%a in ('reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "LastUsedUsername" ^|findstr /ri "REG_SZ"') do echo=%%a

I expect the username to be printed in the screen, but it doesn't happen.

I am sure the Registry value "LastUsedUsername" is not empty, it really has data. Also, the delimiter is a tab, not spaces.

EDIT

If I just type

reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "LastUsedUsername"

... it returns:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon
    LastUsedUsername    REG_SZ    Administrador

This code

reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "LastUsedUsername" ^| findstr /ri "REG_SZ"

... returns:

    LastUsedUsername    REG_SZ    Administrador

Then, when I use the for command, I just get no output from echo.


Solution 1:

You don't need the delims switch, at all, since the default is space, which is what the reg query is returning. In making a bat file for this for loop and registry on a key that I am messing with I get the correct echo, for my instance the "Red" value of the RGB Background color is 55:

for /f "tokens=3" %%a in ('reg query "HKCU\Control Panel\Colors"  /V Background  ^|findstr /ri "REG_SZ"') do echo %%a

Solution 2:

The approved answer is not correct in some situations - if value read from the registry containst white characters i.e. spaces (Program Files (x86)) then it returns only the first part of the value ('Program'). What is I worked out is:

FOR /F "tokens=2* skip=2" %%a in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion" /v "CommonFilesDir"') do echo %%b

The result is C:\Program Files\Common Files

Solution 3:

The syntax of the DOS command is correct. I would question whether you have the correct registry key value. Just type the req query... part into the command line and see what is returns. I am running Win 7 and I do not find the key , LastUsedUsername, defined in HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon