What are some of the lesser know, but important and useful features of Windows batch files?
Guidelines:
- One feature per answer
- Give both a short description of the feature and an example, not just a link to documentation
- Limit answers to native funtionality, i.e., does not require additional software, like the Windows Resource Kit
Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.
(See also: Windows batch files: .bat vs .cmd?)
By using CALL, EXIT /B, SETLOCAL & ENDLOCAL you can implement subroutines with local variables.
example:
This will print
even though :sub modifies x.
Delayed expansion of variables (with substrings thrown in for good measure):
Stops execution and displays the following prompt:
Useful if you want to run a batch by double-clicking it in Windows Explorer and want to actually see the output rather than just a flash of the command window.
Variable substrings:
To quickly convert an Unicode text file (16bit/char) to a ASCII DOS file (8bit/char).
as a bonus, if possible, characters are correctly mapped.
The FOR command! While I hate writing batch files, I'm thankful for it.
would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces. Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd.
You can also use this to iterate over directories, directory contents, etc...