Page 1 of 1

How to do this task?

Posted: 12 Jul 2011 09:42
by mdivk
Hi folks,

I haven't done this for too long, I hope you guys can refresh my brain for it:

I have a folder which stores weekly update files copied from another server. I need to keep only 4 files. So every time I run the batch file, I want to check the number of files, if it's less than 4, then do nothing; if it's more than 4, then find out the oldest one, delete it, then copy the latest one into this folder.

If possible, (I guess it's impossible, I will have to write a .NET program to do it) I also want an email be sent out after the copy/deletion job is done.

Thank you very much.

Re: How to do this task?

Posted: 12 Jul 2011 10:43
by aGerman
Try that:

Code: Select all

@echo off &setlocal
:: delete
pushd "D:\where\your\backup\files\are"
for /f "skip=3 delims=" %%a in ('dir /a-d /b /tc /o-d') do del "%%a"
popd

:: copy
copy "D:\source\folder\file.ext" "D:\where\your\backup\files\are\"


Regards
aGerman

Re: How to do this task?

Posted: 12 Jul 2011 12:06
by mdivk
Thank you so much for your prompt reply. One more question:

How about if I need to make a slight change:

There is always a fix name backup file on server. And the backup file on backup server are named: wk1.bak, wk2.bak, wk3.bak and wk4.bak
When copied to the backup server, how do I delete wk1.bak, and change the existing files from wk2 to wk1, wk3 to wk2, and so on? and then the newly copied one is named as wk4.bak?

Re: How to do this task?

Posted: 12 Jul 2011 12:46
by aGerman
That should work:

Code: Select all

@echo off &setlocal
set /a n=1

:: delete
pushd "D:\where\your\backup\files\are"
for /f "skip=3 delims=" %%a in ('dir /a-d /b /tc /o-d') do del "%%a"

:: rename
if exist wk1.bak set /a n+=1
if exist wk2.bak (if not exist wk1.bak ren wk2.bak wk1.bak) &set /a n+=1
if exist wk3.bak (if not exist wk2.bak ren wk3.bak wk2.bak) &set /a n+=1
if exist wk4.bak (if not exist wk3.bak ren wk4.bak wk3.bak) &set /a n+=1
popd

:: copy
copy "D:\source\folder\file.ext" "D:\where\your\backup\files\are\wk%n%.bak"

Regards
aGerman

Re: How to do this task?

Posted: 12 Jul 2011 13:09
by mdivk
You rock buddy!!! Thank you very much.