Page 1 of 1

copy folder with latest time stamp using batch file

Posted: 20 Feb 2020 09:58
by user124
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

Re: copy folder with latest time stamp using batch file

Posted: 20 Feb 2020 13:57
by penpen
You might want to use xcopy instead of copy (if i remember right; better check first):

Code: Select all

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

Re: copy folder with latest time stamp using batch file

Posted: 20 Feb 2020 14:48
by user124
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!

Re: copy folder with latest time stamp using batch file

Posted: 21 Feb 2020 15:16
by penpen
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