Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

Windows Batch Script : Sort folders and process first folder only

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...