CMD: Quick repeated body file generation

07 Dec

Having come from DOS to Windows, batch commands have been indispensable part of my admin work. Its surprisingly how weak a lot of the Windows administrators nowadays are at writing simple batch scripts. Instead they tend to just repeat what they do with copy and paste using GUI, over and over.

Anyway, batch scripts is not rocket science, but I have seen some that is so good that it can probably launch a rocket! So here is my first batch script sharing that I hope can help some of you out there to improve your work.

Below is something I quickly hacked up because I needed to generate an import file with a list of 14 server names in XML format. The format of the file is a typical header/footer with a repeated body containing different host names.

I basically added a FOR loop into the batch file to generate the body. It makes a call to the procedure :body, which you can treat like another batch file. Few people are aware that you can call a procedure in a batch file. I also only found that out some years ago. Just need to remember to start the procedure with :Name and end with GOTO :EOF, which is effective a return call.

Some may wonder what %~dp0 means. This is a very useful variable substitution for the full path of the current script. Hence if my script is in c:\scripts, %~dp0host.txt will return c:\scripts\hosts.txt. To find out more, type FOR /?.

I have attached my file GENVRD.CMD (please rename ext to cmd) so that you can make sense what I am talking about. You will notice in the script I used ^> and ^< to escape the gt and lt signs.

@echo off
@echo Header Text > myfile.txt

for /f %%a in (%~dp0host.txt) do call :body >> myfile.txt

goto end

@echo REPEAT BODY with %1
@echo REPEAT BODY with %1

goto :EOF

@echo Footer Text > myfile.txt

Leave a comment

Posted by on December 7, 2007 in Scripts, Windows CMD



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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: