I have automated a nightly backup process with Mathematica. I use a task scheduling program to run a longer version of the following .m file below with MathKernel. Functions like Complementmake it easy to copy new files from a working directory to a backup directory, and in general, Mathematica makes it easy to use sophisticated logic along with various file functions in backup operations. I use $Output to redirect the output of print statements to a date stamped processing log so I know what happened. While there is nothing special about the little piece of Mathematica code below, it illustrates some of the things I just described. You could certainly use this approach for much more complicated kinds of processing.
fname="C:\\automation\\"<>"backup "<>datestamp<> ".txt";
Block[{$Output = OpenWrite[fname, FormatType -> OutputForm, TotalWidth -> Infinity]},
workingpath = "E:\\Index Calculation\\";
backuppath = "C:\\Dropbox\\Index Calculation\\";
Print[datestamp];
Print["Backing up "];
Print[workingpath<> " to " <>backuppath];
SetDirectory[backuppath];
backupfiles = Select[FileNames[], ! DirectoryQ[#1] &];
SetDirectory[workingpath];
workingfiles = Select[FileNames[], ! DirectoryQ[#1] &];
missingfiles = Complement[workingfiles, backupfiles];
If[Length[missingfiles] == 0, Print["\nNo files missing in " <> backuppath] ];
Close[$Output]; ]
I simplified the code above to make it brief; "datestamp" is actually:
DateString[{"Year", "Month", "Day", " ", "Hour", "Minute", "Second"}]
To archive instead of overwrite a file that changes daily but that I'd like to keep a rolling history of, I use the following strategy:
If[FileExistsQ[indexname],
tag=DateString[FileDate[index <> " Index.xlsx"],{"Year","Month","Day","Hour", "Minute","Second"}];
newname = StringReplace[index<>" Index.xlsx",{".xlsx" ->" "<>tag<> ".xlsx"}];
Print["Changing index file to " <> newname];
If[!FileExistsQ[newname], RenameFile[indexname, newname];];
];
You can create a list of sub-directories for processing with FileNames and Select (I prefix their names with "@" if I want to keep them out of the list). With this approach, any new sub-directory you create will be automatically included.
SetDirectory["E:\\Index Calculation\\"];
dlist = Select[Select[FileNames[], DirectoryQ[#]&], StringTake[#,1] != "@"&];
Do[
index = dlist[[i]];
Print[index];
(*do automation stuff*)
,{i, 1, Length@dlist}]
Although it's the final answer was simple, it took time for me to figure how to run backup.m automatically. I use VisualCron to run a .bat file containing:
Mathkernel -script backup.m
I would rather run backup.m directly, but can't get Cron to co-operate.
As Kuba says, Mathematica makes everyday programming tasks easier.