0

I'm trying to use the value of an environment variable I capture from a registry key in a batch script, but for whatever reason unknown to me, the variable does not get expanded.

However, I can get it resolved if I do not capture it from the registry.

This is the script:

ECHO ON
SETLOCAL ENABLEDELAYEDEXPANSION
CLS

FOR /F "tokens=2*" %%a IN ('REG QUERY "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop" 2^>^&1^|find "REG_"') DO @SET SHORTCUTDESTINATION=%%b
ECHO %SHORTCUTDESTINATION%
PAUSE

SET VALUEFROMREGISTRY=%SHORTCUTDESTINATION%

ECHO %VALUEFROMREGISTRY%
PAUSE
ECHO %USERPROFILE%
PAUSE

This is the outcome - Results within the red rectangle are not resolved; in green, they are.

batch

What am I missing?

Daniel Santos
  • 188
  • 2
  • 15
  • The value you are extracting is supposed to be of value type `REG_EXPAND_SZ`. As such its value should contain a variable for expanding. In order to do that you would need to expand that value by `Echo`ing the value within another cmd.exe instance, through another `For /F` command. For example: ```@For /F "EOL=H Tokens=2,*" %%G In ('%SystemRoot%\System32\reg.exe Query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /V Desktop 2^>NUL ^| %SystemRoot%\System32\find.exe /I "REG_"') Do @For /F "Delims=" %%I In ('Echo "%%~H"') Do @Set "SHORTCUTDESTINATION=%%~I"```. – Compo Dec 12 '22 at 18:34
  • 1
    I suggest to take a look at [How to create a directory in the user's desktop directory?](https://stackoverflow.com/a/58516212/3074564) – Mofi Dec 12 '22 at 18:59

1 Answers1

1

You can use call echo and call set to force cmd to expand the %userprofile% system variable.

ECHO ON
SETLOCAL ENABLEDELAYEDEXPANSION
CLS

FOR /F "tokens=2*" %%a IN ('REG QUERY "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop" 2^>^&1^|find "REG_"') DO @SET SHORTCUTDESTINATION=%%b
ECHO %SHORTCUTDESTINATION%
call echo %SHORTCUTDESTINATION%
PAUSE

SET VALUEFROMREGISTRY=%SHORTCUTDESTINATION%
call SET VALUEFROMREGISTRYCALL=%SHORTCUTDESTINATION%

ECHO %VALUEFROMREGISTRY%
ECHO %VALUEFROMREGISTRYCALL%
PAUSE
ECHO %USERPROFILE%
PAUSE
OJBakker
  • 602
  • 1
  • 5
  • 6
  • To make it shorter, couldn't you just use `FOR /F "tokens=2*" %%a IN ('REG QUERY "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop" 2^>^&1^|find "REG_"') DO @call set "SHORTCUTDESTINATION=%%b"` here? – Qwerty Dec 12 '22 at 19:09
  • @Qwerty Yes in this case that would be sufficient. But if you would want to change such a registry key than you should do that only with the unexpanded key (the one with %userprofile% in its value). – OJBakker Dec 12 '22 at 19:58
  • The CALL SET did the trick @OJBakker - Thank you! – Daniel Santos Dec 12 '22 at 20:42