When you’re stuck with oldskool Windows batch scripting, you can get the feeling your being transported back in time to the DOS age where New Wave was popular and Bill Gates was looking like a geek. Well, yeah, he still looks like a geek, but at least New Wave is dead, thought the haircuts were always good for a laugh.
Unlike the appearance of Bill, things have however changed on the batch scripting front, and the command line of the modern Windows OS has significantly been updated to support kick ass functionalities such as:
Ok. That’s not so cool. Some even say it’s evil. But combined with a label, you can jump to anywhere in your scripts code, which allows you to divide the script up into modules for reuse. Awesome? Naah, but wait, it gets better.
Labels are defined by putting a colon in front of your labels name btw, like
:foobar in this example.
That jumps to the end of the script, at any time. The :EOF label is a predefined one, so you don’t have to put a label at the end of the script to be able to do that. This one becomes really handy once you start using stuff like
call :foobar c:\temp\*.*
Just a fancy goto right? Well yeah, sort of. Call is normally used to call other batch scripts, and return to the calling script after execution. Sort of like a function call but with a batch file. Well, now you can use them as function calls if you use a label name as the “script” to call, as in the example above. It gets even better. You can even pass parameters along with a call statement like this. The call will treat the called “function” as a separate batch script, which means you can use the argument environment variables %1 .. %9 (or %*) instead of using globally defined variables. Wicked huh? For example:
echo Kiss your files goodbye!
del /s %1
So now you can call this handy function with any kind of path to delete your files. Be careful though. It works. See the :EOF? Well, you need that to quit that virtual batch script that’s being called. Handy huh?
The if statement works with code blocks too now, and you can have your tests ignore case by adding the /i parameter.
if /i "%1"=="foobar" ( echo "foo bar" ) else ( echo "not so foo bar" )
It’s starting to feel like real programming, doesn’t it?
set has also been expanded beyond merely setting an environment variable. It can now do some basic calculations (
/A), prompt for input (
/P) or even do some string manipulation (see
for statement should also be on your list of things to check if you want to do some serious batch processing. It’s really powerful. Besides the expected 1 to X loop you can use this to parse a file line by line, or process all files in a given directory.
Can’t wait to get started? Well, to figure out more commands just open up a command shell on your Windows box and type help. Each of those commands can be useful (check out
shift if you want to parse the command line) for writing that kick ass batch script.
Or maybe just learn Python oslt. That really kicks ass.