copy folder with latest time stamp using batch file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
user124
Posts: 4
Joined: 20 Feb 2020 09:51

copy folder with latest time stamp using batch file

#1 Post by user124 » 20 Feb 2020 09:58

Hello,

I am a new user trying to create batch files for the first time. I am trying to create a batch file that will detect the folder with the latest time stamp, copy the entire folder and sub folders and paste into another folder. The batch file will run everyday as new folders are added on a daily basis.

I have been using the code below but it only copies the file with the latest time stamp and not the folder. Any help would be appreciated. Thanks!

@echo off
setlocal enabledelayedexpansion

set "source=\\network_path\test"
set "dest= \\network_path\test2"

pushd "%source%"

for /f "tokens=*" %%G in ('dir *.* /b /a:d /o:d') do SET newest=%%G

copy "!newest!" "%dest%"
popd
cmd /k

penpen
Expert
Posts: 1822
Joined: 23 Jun 2013 06:15
Location: Germany

Re: copy folder with latest time stamp using batch file

#2 Post by penpen » 20 Feb 2020 13:57

You might want to use xcopy instead of copy (if i remember right; better check first):

Code: Select all

xcopy "!newest!" "%dest%" /E
penpen

user124
Posts: 4
Joined: 20 Feb 2020 09:51

Re: copy folder with latest time stamp using batch file

#3 Post by user124 » 20 Feb 2020 14:48

Thanks for your reply penpen. I tried using xcopy but it didn't copy any files. I tried using

Code: Select all

xcopy /s /e /i
and it copied over the contents inside the "test" folder. I would like to copy over the "test" folder and the sub folders inside it. Would you have a solution for this?

Thanks!

penpen
Expert
Posts: 1822
Joined: 23 Jun 2013 06:15
Location: Germany

Re: copy folder with latest time stamp using batch file

#4 Post by penpen » 21 Feb 2020 15:16

user124 wrote: it copied over the contents inside the "test" folder. I would like to copy over the "test" folder and the sub folders inside it.
I am a little bit confused, you said before, you only wanted to copy the sub-folder with the latest timestamp (at least i interpreted it that way):
user124 wrote:that will detect the folder with the latest time stamp, copy the entire folder and sub folders
Or do you mean you want to copy to a subfolder within the destination folder (meaning your destination folder is just the parent element of the real destination folder)?
If so the following might be what you are looking for:

Code: Select all

@echo off
setlocal enabledelayedexpansion

set "source=\\network_path\test"
set "dest=\\network_path\test2"

pushd "%source%"

for /f "tokens=*" %%G in ('dir *.* /b /a:d /o:d') do SET newest=%%~nxG

xcopy "!newest!" "%dest%\!newest!" /s /e /i

popd

goto :eof
penpen

Post Reply