Friday, May 09, 2008

Batch Scripting Tips

Here are some BATCH script tips which I discovered on the web that helped me a lot in Windows.

Why did I use BATCH scripts? Why not Ruby or Python, or even JScript? Well, if you're writing some basic automation which should be run on deployment PCs, etc. BATCH files are standard and sufficient enough to work. Installing Ruby, etc. on all the machines first is a pain and an unnecessary step (IMO).

I am keeping this for future reference. There is a website that is dedicated to this kind of thing:

Now I assume you have basic BATCH scripting knowledge.

Hiding Commands
If you want to hide all the ECHO and COPY, etc. commands from being displayed, insert this in the top line of your script file:


Printing an Empty line
Sometimes you want to produce an empty line in the console output. This can be accomplished by:


Note: The . (DOT) is directly after the ECHO command and has no spaces in between!

If you have a variable to hold certain values, to set it you type:


You would preferably type the value without quotes, since the quotes will be included in the value.
Using a value:


Which should output:


User input
If you would like the user to type in something, you use the /P option of the SET command:

SET /P CHOICE=Type a letter and ENTER:

This will output:

Type a letter and ENTER:

Now the user can type in something and press ENTER. This will store the typed in text in the variable CHOICE.

If you want to take a substring from a variable, you can do so by:


This will take the 'User Input' sample's CHOICE variable's 1st character. As you have noticed, it starts with the variable's first index (0) and by using length (1), like in Java's substring() method, you will get the first character of the variable.

If statements
Now, if you want to do a check by comparing a variable's value by a certain string, you can make use of the IF command.


CHOICEA and CHOICEB are just labels to where the batch process should jump to if the given conditions are true. It doesn't have to be GOTO statements, it can be single statements, such as ECHO or SET. The /I option tells the IF statement to do a case-insensitive comparison. If you compare your variable against a string, you have to place it inside quotes, like above.

A label is a place to where the batch processor jumps to after executing a GOTO statement. Example:


Current path variable
This will output the current directory:


Path of batch file
Sometimes you want to work relatively from the path of the batch script file, rather than the current directory.

ECHO %~dp0

This will output the path of the batch file that is running.

No comments: