I'm using this command on the Windows 10 Command Prompt to check if a folder exists and if it doesn't, create it. The weird thing is, it doesn't work the first time I enter it but the second, third, etc. it does, as if the variable values don't update the first time I run it.
set "folder=C:\Users\%USERNAME%\Desktop\New folder" &&
set "subfolder=new" &&
( IF exist "%folder%\%subfolder%" ( echo The "%subfolder%" subfolder already exists. )
ELSE ( mkdir "%folder%\%subfolder%" && echo Created the "%subfolder%" subfolder. ) )
1st execution output:
The "%subfolder%" subfolder already exists.
That output is wrong. The subfolder doesn't exist because it hasn't been created yet. Why doesn't the variable get expanded?
2nd execution output:
Created the "new" subfolder.
That's what it should say the first time.
3rd execution output:
The "new" subfolder already exists.
That's what it should say the second time.
How can I fix the command so it runs right the first time?
Ok. In your example you posted four lines. However, because the first two lines ends in &&
and the fourth one starts in ELSE
(that it is not a valid command), I assume that your example is really one long line...
If so, then your code will work if you just split it in these two separate lines:
set "folder=C:\Users\%USERNAME%\Desktop\New folder" && set "subfolder=new"
IF exist "%folder%\%subfolder%" ( echo The "%subfolder%" subfolder already exists. ) ELSE ( mkdir "%folder%\%subfolder%" && echo Created the "%subfolder%" subfolder. )
If you want to know the reasons for this change, then you should search for "Delayed expansion" term in this or any other cmd.exe commands related site. A brief summary is this:
You can not define a variable and %expand% it in the same line. To do so, you need to Enable Delayed Expansion and use exclamation marks instead of percent signs to expand !variable!
values that had changed in the same line.