I was going over an example batch file that was able to display a variable outside of a loop:
@echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%
It's able to echo %_tst%
because it's declared at the top before the loop.
I tried it with a batch file that I'm currently using:
@echo off
cls
setlocal EnableDelayedExpansion
set drive=R:
set counter=0
FOR /F "tokens=*" %%c IN ('dir %USERPROFILE%\Backup /B') DO (set /A counter+=1)
if %counter% GTR 0 (
echo Total # of folders: %counter%
) else (
echo No folders to move
)
It works, but, when I try to check if a drive is available before executing the loop, I have the use !counter! to access the variable, like so:
If I don't, it just says "Please press any key to continue."
because of the pause.
@echo off
cls
setlocal EnableDelayedExpansion
set drive=R:
set counter=0
if exist %drive% (
FOR /F "tokens=*" %%c IN ('dir %USERPROFILE%\Backup /B') DO (set /A counter+=1)
if !counter! GTR 0 (
echo You have !counter! folder(s)
) else (
echo No folders to move
)
)
pause
exit /b
Why is it that when I have the if statement checking if my drive is available I have to use !counter!
?