Tuesday, 28 September 2010

How to create a script to automatically sort your files into folders based on creation date...

Ok – on to another script... and this one is sweet and simple. This script performs a filing task on files by date i.e. it will get all the files in a directory and move them into folders based on their date.

I have gone for the following file structure:

.\YYYY\MM\DD\my_file_n.file

Please note that this script has been tested for Windows 2003 Server ONLY (see previous post for determining version numbers) and may not work on your target system without some minor tweaking!

Right – onto the meat... first we have to loop through all the files in the directory (I have specified .XML files only) and extract the name (%%~x) and the timestamp (%%~tx):

for %%x in (*.xml) do call :File_File "%%~tx" "%%~x"

The next bit (as you can see above from the call to the method File_File) is to pass these to a procedure to parse the date, create the directory and move the file:

First we will have to extract the date parts (this is where your OS version or Date locale may trip you up – tweak as needed!) – you can see we specify the delimiters as ‘:’ and ’/’ to split the timestamp into the bits we need and then assign them to variables from the resulting 5 part array using the ‘%%a’ (first element) to ‘%%e’ (fifth element):


for /f "tokens=1-5 delims=/: " %%a in (%1) do set year=%%c&set month=%%b&set day=%%a&set hour=%%d&set minute=%%e

We then build the variable containing the file path where the file will be stored:

Set FilePath=%year%\%month%\%day%

We check to see if it exists and create it if not:

IF NOT EXIST %FilePath% MD %FilePath%

Then move the file:

move %2 "%FilePath%\%2"

Simples!



No comments:

Post a Comment