Many developers never bothered to learn much about DOS because of the widespread availability of GUI applications, like Windows Explorer. However DOS is still useful in many cases, and essential to automate almost anything. Therefore it's worth knowing a couple basics beyond just making directories and copying files.
The Call Statement
As you break a big task into smaller ones, you will need to have one script call another. However DOS scripts effectively each run in their own thread, and are not like normal .Net methods where the caller automatically waits for the called-method to finish. The question to ask is "Do you want the parent script to wait for the child script to finish?"
- Yes: Then use the call keyword, like: call Child.bat.
- No: Then simply the script directly, like: Child.bat.
This can be vital when having a main host script call a bunch of sub-scripts in sequence.
Passing in Parameters
DOS Scripts can take in and pass out parameters. The two batch scripts below show how:
Parent.bat: Pass the parameters into the child by adding it after the script being called. This passes in two parameters, "Hello" and "World!"
Child.bat: Access the parameters being passed in by %n, where n is the ordinal of the parameter (starting at 1), such as %1 or %2.
Using Environmental Variables
DOS supports variables. You can create your own or use existing environmental variables, such as: SystemDrive, TEMP, USERNAME, windir. Type set at the command line to see all the existing environmental variables. For example, the System Drive may vary from machine to machine. Therefore instead of hard-coding it as "C", use %SystemDrive%.
You can also create your own variable using the syntax: SET [variable=[string]]. For example, run the following DOS commands:
The Echo will output "Hello World", which is the value of the variable. Variable Scope encompasses all child windows opened by the parent window.
If all you have is a hammer, everything looks like a nail. By being aware of what good-old DOS has to offer, it opens up your options when trying to automate tasks.