How to do this task?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
mdivk
Posts: 15
Joined: 12 Jul 2011 09:37

How to do this task?

#1 Post by mdivk » 12 Jul 2011 09:42

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.

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to do this task?

#2 Post by aGerman » 12 Jul 2011 10:43

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

mdivk
Posts: 15
Joined: 12 Jul 2011 09:37

Re: How to do this task?

#3 Post by mdivk » 12 Jul 2011 12:06

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?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to do this task?

#4 Post by aGerman » 12 Jul 2011 12:46

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

mdivk
Posts: 15
Joined: 12 Jul 2011 09:37

Re: How to do this task?

#5 Post by mdivk » 12 Jul 2011 13:09

You rock buddy!!! Thank you very much.

Post Reply