Tuesday, July 29, 2008

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):

"%~dp0..\Other.bat"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.