Question

This is my script. In this case I'm trying to get the last file (when sorted alphabetically) of the directory. Whenever I run it, the last file in the 6th folder is given out in every iteration. What is wrong with this script?

@echo off
cd folder1\folder2

for /D %%G in (*) do (
    echo %%G
    cd %%G

    for /f %%F in ('/b/a-d/on') do (
        set last=%%F
    )   
    echo %last%
    cd..
    pause   
)

cd..
cd..
Was it helpful?

Solution

Like this it work:

Put this in your working directory and run it.

@echo off
setlocal EnableDelayedExpansion
for /d %%a in (*) do (
for /f "delims=" %%F in ('dir /s/b/a-d/on "%%a"') do set $last="%%~nF%%~xF"
echo last of %%a is !$last!
)

echo Done...
pause

Edit :

To make your code working :

@echo off
setlocal EnableDelayedExpansion

for /D %%G in (*) do (
echo %%G
cd %%G\

for /f "delims=" %%F in ('dir/b/a-d/on') do (
    set last=%%F
)   
echo !last!
cd..
pause   
)

cd..
cd..
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top