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

batchwindows-registry

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.

Best Answer

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
Related Question