Batch scripts to LOCK a file!!

11 04 2006

Believe it or not, but batch scripts have done it again for me. My requirement was to get a line number from a file and corresponding to that get the name of the windows image which was to be installed, and I was in a big delimma, as I could use only batch scripts or write a C program. Well! I knew that the exe in C would be more reliable and compatible over platforms, but after all my initial image was being installed using only a simple pure DOS interface with networking capabilities… So I resorted to batch… and voila!!

All thanx to Mic at batch World, I was finally able to create what i required. So here is the geeky code, which I am sorry after writing about all that documentation stuff, I was just tooooo excited as to not touch πŸ™‚ I have although given the explanation below the code as to what the code is doing :

@echo OFF
if exist c:\lockfile goto loop
if not exist c:\lockfile >C:\lockfile echo locked
goto end

@echo OFF
setlocal EnableExtensions EnableDelayedExpansion
for /f “delims=” %%a in (‘type C:\Count’) do set num=%%a
for /f “delims=” %%a in (‘type C:\MyFile.txt’) do (
set /a count+=1
if !count!==%num% set name=%%a

set /a num+=1
>C:\Count echo/%num%
pause Wait…
del C:\lockfile
IMAGE.EXE -harddisk:0 -filename:%name%

What I am doing over here is open 2 CMD windows and after copying the above code and creating the 2 file called ‘Count’ and ‘MyFile.txt’ in the C: drive [the ‘Count’ can have content like the numeral 3, and the MyFile.txt can have any number of lines with names of you and your various girlfriends… ;-)]

If you have copied the code above to lets say ‘my.bat’, then in both of these call the file by simply typing at the prompt:-

The first one to run will pause and wait for you to press any key, run the second also, and it will go into a loop, until you click any key in the first.

And Voila!! you have a lock file feature implemented, while you can modify a file which is to be used by multiple processes and each have to have a different value from the Count file, which is then corresponding to a line number in the MyFile.txt file… πŸ˜€

In the actual scenario the pause line will be removed as i do not require it in the actual project and it will hinder my true automation effort if a person has to come there and press any key for the system to continue… πŸ˜€

So folks that does it, now do you wish to go in for BATCH … !! πŸ™‚




Leave a Reply

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

You are commenting using your 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: