Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a directory of folders and I am trying write a windows batch script to sort the folders by name and then copy the files in the first folder to a different location.

Directory

  • 2020-09-02
  • 2020-09-01

Here "2020-09-02" and "2020-09-01" are folders (or sub-folders under the folder 'Directory'). Each folder (2020-09-02 and 2020-09-01) has a set of files inside them.

I need to pick the folder 2020-09-01 (as that is the oldest folder) and copy the files inside the folder 2020-09-01 into a different location, and then delete the folder 2020-09-01.

I do not need to do this in a loop (to process all folders under 'Directory'). I just need to be able to pick the folder with least date and process that folder alone.

I am good with the code to copy the files in a directory to a different location, but having trouble to be able to select the folder with oldest date (without a for loop).

Any help is appreciated. Thanks in Advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the /o switch from dir to use the oldest item, the /ad switch to only show directories and the /b switch to view the directories without volume label and directory info, only shows the files.

rem Ensure that 'oldest' variable isn't being used before.

set oldest=

for /f "delims=" %%A in ('dir /od /ad /b') do if not defined oldest set "oldest=%%A"
rem Oldest folder is stored into %oldest%

I don't understand why you don't want to use a for loop.
for statement is probably the most powerful one in batch, take a look at SS64 and Rob van der Woude for explanation and examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...