0

I created a batch file that searches for the users desktop folder in Windows.

for /F "skip=2 tokens=3* delims= " %%a in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop') do set DESKTOP=%%a

If my desktop folder isn't in C:\Users\User\Desktop, it will work and return the correct folder, for example in my case E:\User\Desktop. If the desktop folder is in C:\Users\User\Desktop, the script above will result into %USERPROFILE%\Desktop. Later in the script I try to create a new file on desktop. In the first option it will work, because E:\User\Desktop is a real directory. In the second one it won't because obviously %USERPROFILE%\Desktop doesn't count as a directory.

echo start javaw -jar "path/to/program.jar" >"%DESKTOP%\Start program.bat"

How to get it work on both situations?

Doing

if /I "%DESKTOP%" EQU "%USERPROFILE%\Desktop"

doesn't help because it is the same as

if /I "%DESKTOP%" EQU "C:\Users\User\Desktop"

2 Answers 2

2

You could use call to expand the variable:
call set desktop=%desktop%

Sign up to request clarification or add additional context in comments.

1 Comment

+1; I was going to provide an expanded version of that answer when I was asked to make breakfast for the family. LOL
2

You need an extra round of normal expansion. As wmz has already answered, you can get that extra round by using CALL.

You should be careful about special characters like & or ^ that are valid in folder and file names. I recommend using quotes in your assignment to protect special characters.

call set "DESKTOP=%DESKTOP%"

I am assuming the value of DESKTOP does not already include quotes. All bets are off if you have a mixture of definitions that sometimes include quotes, and other times don't.

Suppose DESKTOP=This & that\%VAR% and VAR=& the other thing. The end result with the quoted assignment using CALL will be correct: This & that\& the other thing.

I have seen & in folder names in the real world, so the quotes are a good thing. However, there is a problem if your value contains ^. A quoted ^ is doubled if passed through CALL.

Suppose DESKTOP=one^two%var% and VAR=^three, the end result of the quoted assignment using CALL will be one^^two^three.

I don't think I have ever run across ^ in a folder name, but it is possible, and there is a solution. You can use CMD /C to get another round of expansion, and use FOR /F to capture the result.

The following will give the correct result of one^two^three. I use "eol=:" because a valid path can never begin with :.

for /f "eol=: delims=" %%B in ('cmd /c echo "%DESKTOP%"') do set "DESKTOP=%%~B"

You do not need to use an intermediate assignment of DESKTOP. In all of the above, you can substitute your FOR /F %%a in place of %DESKTOP%.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.