Tuesday, July 29, 2008

Using parameter qualifiers in Windows shell scripts

Summary: How to extract file information from command-line arguments in batch (.BAT) files.

It may seem archaic, but despite the advancement of more recent Windows command shell tools and technologies -- such as Windows Script Host, PowerShell, etc. -- the original Windows NT® Shell is alive and well. VBScript, and PowerShell scripts may look young and hip, but old and proven batch (.BAT) files still offer the easiest way of performing simple operations, such as copying, moving files, or launching programs.

I have been writing batch files for many years, but I still struggle to remember a few common things such as runtime substitution of parameter qualifiers. Parameter substitution is most helpful if you want to extract parts of a file name. For example, you may want to extract directory path from the full path of the running batch script, so you can build a path for another file located in the same directory. Or maybe you want to use the folder path to access a parent directory. There are many good uses for parameter substitution, so this is how you can do it.

First, remember that command-line parameters are referenced using percent sign followed by the parameter index, such as %0 (references the running batch file), %1 (first parameter), %2 (second parameter), and so on. To extract a part of the path name from the parameter, insert tilde (~) followed by one or more of these specifiers between the percent sign and parameter index (%~fdpnxN, where N is the index of the argument):

QualifierExpands to a...
fFully qualified path name
dDrive letter and colon character
pPath (to a directory) without a drive letter, file name, or file extension (may contain a trailing backslash)
nFile name only without a drive letter, directory name, and extension
xFile extension with a leading period
The following examples show how to extract file information for the running batch script (assume that the script's full path is C:\Scripts\Test.bat):
Returns name and extension of the running batch script: Test.bat

Returns directory and folder path of the running batch script: C:\Scripts\

Returns quoted full path of the Other.bat file in the parent folder: "C:\Scripts\..\Other.bat"
Notice that all samples above use argument #0 (the running batch file), but you can use parameter substitution with other arguments as well. Also, there are other qualifiers, which can be used for parameter substitution, but I did not mention them because they are rarely needed. To learn more about parameter qualifiers in Windows shell scripts, see references below.

Additional references:
The Set, Call, and Shift statements by Richard Charrington (see The call statement section)
Windows NT® Shell Scripting by Tim Hill (the best book on the subject)

No comments: