Wednesday, 5 November 2008

How to Write a Good Old Windows Batch File (GOTO considered useful)

Introduction

This post is about effective batch file writing. No Windows programmer is complete without a working knowledge of batch files. Here are some reasons you would use good old-fashioned batch files as a preferred technology over newer, shinier alternatives:

Advantages of Batch Files
  1. Scripting languages are not installed on client PCs, doing so would be a hassle
  2. Need to run some commands on a network drive which may have partial trust issues if implemented in .NET

Tips and Tricks

  1. For comments, use :: instead of REM. The reasons will become apparent. : is a notation for labels in Windows batch files.
  2. When setting variables do: set VAR="". Every time you use VAR you need to say %VAR%. That's pretty obvious when you're echoing stuff to the screen, but once you start to get into conditional statements, it can be easy to forget the necessary %% delimiters e.g. you need them when doing: mkdir %VAR%, or IF EXIST %VAR% GOTO VAREXISTS:, or COPY %SOURCE%\*.* %TARGET%\. See how ubiquitous percentage signs are in real-life batch file writing!
  3. To access command-line arguments use %1, %2, .. , %n. Again the percentage sign - this time operating in a unary capacity!

@echo off (TRACE OFF)

Worth adding a word on the @echo off statement oft-seen atop many a batch file. echo off prevents commands echoing themselves irritatingly to the console; the @ prefix is a self-reference trick which applies the command to itself.

Tricky Syntax

Batch files have some syntactical tricks which seem a little awkward. Here is a summary:

:~n (colon-tilde) -> extract the first (or last if n is negative) n characters from a variable e.g. %PATH:~-10% will extract the last 10 characters from the path.

:~m,n (colon-tilde-comma) -> a small variation of colon-tilde. m characters offset, then next n characters. m=0 means extract all the characters. This is a substring function.

%~dp0 (percent-tilde-drive-path) -> %0 determines where the batch file is running from (a la %1, %2 et al) and the dp produces the drive letter and path - so this tells us which dir/path we are running from. %~dp1 will do the same for variable 1 (seems a bit weird to do that).

%~sp0 (percent-tilde-short-path) -> same as dp0 only returns "short path" (i.e. drive letter is missing so C:\WINNT becomes \WINNT)

Google groups has a post identifying even more % codes; take a gander here.

Bits and Bobs

To compose powerful batch scripts you need a good working knowledge of DOS commands that are legal under Windows. The site here gives a good Vista-focused introduction.

No comments: