Toivo Talikka

Total Data Pty Ltd

Computer system installation, support and IT management consultancy

Forestville NSW Australia        tel 0410 532 923       email toivo@totaldata.biz

Toivo's TechTips Corner

Batch File Example

This tip shows how to prompt for keyboard input in a batch file and call a subroutine, another batch file.

Software Environment

Windows XP SP2

Word of Warning

If you are not familiar with batch programming, please do not try to modify and run the following routine at home.

If in doubt, call an IT specialist to provide the support instead.

Directory Maintenance in Windows XP

We need to produce a simple maintenance routine which deletes files older than 90 days, based on the date the file was last modified, from folders with the name Archive1, Archive2 and so on.

The routines have been named using the file name extension .cmd. The extension .bat would work exactly the same way.

The main routine ArchiveMaint.cmd prompts for a date in the format mm-dd-yyyy. It give the user a chance to cancel the job by pressing Ctrl-C before any deletions happen. If any other key is pressed, the main routine produces a directory listing consisting of the names of folders starting with Archive under the current directory.

The main routine calls the subroutine once for every folder name starting with Archive, passing the date and the folder name as parameters to the subroutine.

The subroutine creates first a working directory for its use. Because there is no command available (none that I know of) to delete files based on the last modified date, the versatile XCOPY command copies all newer files than the deletion date from the current Archive directory to the working directory. It then deletes all the files from the current Archive directory and copies the contents of the working directory, the files we want to stay in Archive, back to the current Archive directory.

Main Routine ArchiveMaint.cmd

@echo off
set /P date_in=Enter date mm-dd-yyyy:
@echo date = %date_in%
@echo press Enter to continue
@echo press Ctrl-C to stop the deletion of older files from Archive folders
pause
@echo starting loop
for /F %%i in ('dir /AD /B /S Archive*') do archivesub.cmd %date_in% "%%i"
@echo end of loop

Subroutine ArchiveSub.cmd

@echo off
@echo parameter 1: date mm-dd-yyyy %1
@echo parameter 2: directory path %2
@echo create an empty work directory
rmdir /S /Q workdir
mkdir workdir
@echo copy files newer than the date to workdir
xcopy %2\*.* workdir\. /D:%1 /C /Q /K /X
@echo delete all files from directory
del /Q %2\*.*
@echo copy files back from workdir
xcopy workdir\*.* %2\. /C /Q /K /O

Made With Cascading Style Sheets Valid CSS! Valid XHTML 1.1!