Translate

Saturday, 22 September 2012

Batch job for copying latest file and delete older file on network path

Hello everyone,
Today I am posting a scenario where user have to be copy and delete the files from local server to remote server on windows. And delete the older files (due to space issue) from remote server via manually.
Initially (when someone join the new organization) it is a most Favorited time pass job (the person who have nothing to do on his office) for him ;). But after a time it will become more boring and time consuming task (coz u have to login via mstc on main server and copy the file from mouse intelligent people may use CTRL+C and then open the share location and paste it).
So I am giving you a small script which will do this task for you either on single click or automatic ( by scheduling it in scheduler job).
So here are the steps for same...


Step 1. First you will create the network drive for the shared folder where you are moving or copying your   file. Because you are copying and moving so I am assuming that you have the write privs on it.

Crete the network drive for shared folder...
on command prompt type.

net use N: "<shared_location>"

Here N could be any alphabet which is represent the share location as a drive in my computer.

(In my case it like this - net use N: "\\192.168.1.1\Oracle\reports\cache")

Step 2: Now you can see the N: in my computer, through which you can directly go to the shared location.
            
            Now find the most recent file to copy from local server to remote location.

FOR /F "delims=" %%i IN ('DIR "<You_directory_path_for_copy>\*.*" /B /O:D') DO (SET NewestFile=%%i)

this command will find the most recent file either for current date or time.

Step 3: Now copy that file to remote server...

xcopy "<You_directory_path_for_copy>\%NewestFile%" "N:\"

here the path is same from which we need to copy the file to remote server and N: is the location for remote shared server.

Step 4: after copying this if you need to delete the old file from any location use this script. In my case i am deleting the file from remote location i.e. N: which is older then 7 days.

forfiles -p "N:" -s -m *.* -d -7 -c "cmd /c del @path"

Tadaaa... your new file is copied and oldest file has been deleted.Now you can put all these script in just one notepad file and save it as .bat extension. 


Thanks... :)









No comments:

Post a Comment