hi,
i’m trying to semi-automate a batch file of mine for file backups. i’m using an ‘if’ statement to determine (by comparing to %~d0) if the batch is being run from the backup drive (so use %~d0) or the C: drive (so prompt user for drive letter).
my script seems to work fine from the backup drive, but is ‘funny’ if run from the C: drive.
‘funny’ means that i have to input the drive letter three times before the letter is actually ‘set’.
i have added an echo of the resulting drive letter variable, and in each of the first three trys, this is what i get:
1) your drive letter is:
2) your drive letter is: :
3) your drive letter is: i:
+) your drive letter is: i:
the other quirk is that, if i comment out the if statement, and have JUST the user prompt, the variable is set fine.
here is the script:
::determine if program is run from local or other drive IF %~d0==C^: ( ECHO. ECHO ============================ ECHO START ECHO. ECHO Please attach the backup drive. ECHO. :: set drive letter manually SET /P L="Type the drive letter, then press ENTER: " :: the caret character is used before special symbols SET D=%L%^: ECHO Your drive letter is: %D% PAUSE CLS ) ELSE ( ::set drive letter of batch file automatically SET D=%~d0 )
this is my first ever batch script, but this quirk has got me stumped. has anyone experienced this before? can anyone see where i’ve gone wrong?
thanks in advance,
agnieszka.
I don’t think you need special handling of colon. But use delayed expansion to make IF blocks work.
================================
@echo off & setLocal EnableDELAYedeXpansion
IF %~d0==C: (
SET /P L=”Type the drive letter, then press ENTER: ”
SET L=!L!:
ECHO Your drive letter is: !L!
) ELSE (
SET D=%~d0
)
Whenever you’ve got a series of commands inside brackets (i.e. in your case it’s the IF-block) then those commands are loaded into the interpreter all at once, and all %variable% expansions are performed before the commands are executed. So in your SET D=%L%^: the %L% gets expanded to the value of L at the start of the IF block, and does not see the changed value after the preceding SET/P command.
To fix this, you need to use delayed expansion. At the start of your batch file, put
SETLOCAL EnableDelayedExpansion
and use !L! instead of %L% (and of course !D! instead of %D%). Type SET /? for more details.