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?

2
  • 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 Echoing 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". Commented Dec 12, 2022 at 18:34
  • 1
    I suggest to take a look at How to create a directory in the user's desktop directory? Commented Dec 12, 2022 at 18:59

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 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).
The CALL SET did the trick @OJBakker - Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.