1

Hello Batch File experts,

I wrote this piece of code which will print the Latest file version present in the folder in comparison to file name sent as argument, however these line seems to work accordingly when I remove the outer for loop, which I designed to loop as many time as CLI arguments.

FOR /f %%f IN ('DIR /b %%a.*.zip') DO @SET last=%%f
ECHO %last%

Full code :

cd C:\Users\batch\Desktop\test
chdir


set arg1=%1
set arg2=%2
set list=%arg1% %arg2%


(for %%a in (%list%) do (


FOR /f %%f IN ('DIR /b %%a.*.zip') DO @SET last=%%f

ECHO %last%

)) 

pause

what am I missing here because of which variable last is not set with value when outer loop is present which works perfectly without it.

Thanks,

3
  • The echoing of your variable is in the wrong place, you've got a variable named last which is only technically last at the end, not throughout. (it is technically only echoing every file and setting to the last modified matching file of the latest found argument). Commented Nov 30, 2016 at 13:39
  • Possible duplicate of Use a variable in a 'for' loop Commented Nov 30, 2016 at 13:54
  • Too many people use for loops as the default coding method with no thought as to possible alternatives, there's no reason why alternatives ignoring !last! or call %%last%% should not be proposed. Commented Nov 30, 2016 at 13:57

2 Answers 2

0

Might I suggest you use SHIFT instead:

@Echo Off
SetLocal
If %1'==' Exit/B
If /I Not "%CD%"=="%USERPROFILE%\Desktop\test" (
    PushD "%USERPROFILE%\Desktop\test" 2>Nul&&(Set _=PopD)||Exit/B)
:Loop
For %%A In ("%~1*.zip") Do Set "last=%%A"
Echo=%last%
Shift
If Not %1'==' GoTo Loop
%_%
EndLocal
Timeout -1

This of course means that you are free to use it with more than two arguments!

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

1 Comment

Thanks for this solution, its exactly what I was looking. Now I will try to understand the logic.
0

You need to use delayed expansion (about ten thousand SO items on this) or use a subroutine or

call echo %%last%%

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.