Drawing Blanks

Premature Optimization is a Prerequisite for Success

Zen and the art of batch files

leave a comment »

I often use batch files for quick and dirty scripting tasks. Much more often than the modern scripting tools like Windows Scripting Host and Powershell. Because I’m familiar with the concepts of batch scripting since DOS 3.0. Figuring out how to accomplish a simple task using the modern tools would take me longer than writing it as a bat file. Even though bat files are outdated they have been evolving. The capabilities of cmd scripting and the command line utilities in Windows 7 and Windows Server are way superior compared to DOS.

I’d like to share some bat file tips and tricks using this example (provided as is, for demo purpose, not intended for production use):

@echo off
rem Recursively Deletes all files older than the specified age
rem from folders specified in the folderList file and logs output to a file.
rem folderlist file format: "<path>",<mask>,<maxAgeInDays>
rem e.g.: "C:\aaa",*.tmp,30

(set folderList=%~dp0folderList.txt)
(set logpath=%~dp0)
(set datestamp=%date:~10,4%-%date:~4,2%-%date:~7,2%)
(set log=%logpath%\%datestamp%.log)

echo %datestamp% %time% >> %log%
for /F "tokens=1-3 delims=," %%f in (%folderList%) do (
echo %%f %%g %%h >> %log%
forfiles /p %%f /m %%g /d -%%h /s /c "cmd /c if @isdir==FALSE echo @file >> %log% & del @file >> %log%"

Things to notice:

  1. The parenthesis around (set var=val). I use them to avoid the blank space issue.
  2. What is %~dp0 ? It is the path where the batch file is located. %0 is the full path to the current script, and the ~dp parses the drive and path out of it. This variable is especially useful in Windows Vista and higher since when you run the script “as administrator” it is not started in the folder in which it’s located.
  3. Parsing the %date% variable using ~Pos,Len to create the log file name. Note that this method relies on the date format set in the system locale.
  4. Using the for /f operator to parse a text file.
  5. The forfiles command.

Written by bbzippo

11/26/2011 at 2:52 am

Posted in programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: