Batch File Tips and Tricks
Intro / WarningFirst, I'm not going to cover the basics. There are plenty of sites out there for that. I'm just going to jump right into some of the more complicated stuff. I might explain some of it if I have time, but for the most part I'll just be give short descriptions and example usage. Second, I just want to warn you that while batch files can save you time and make life easier, you can really screw up your system if you aren't careful. As good rule of thumb, make sure you *test* your scripts thoroughly with ECHO statements. ESPECIALLY before you use any commands that will change, move, or delete things on your computer such as ERASE/DEL (Delete File), RD/RMDIR (Remove Directory), FORMAT (Format Hard Disk/Floppy), REN/RENAME (Rename Files), MOVE (Move File), REPLACE (Replace File), and probably some others that I missed. I'll be using the Windows XP/NT Command Prompt for everything here: Not Powershell, VBScript, or good ol' fashioned DOS (yes, there are some differences).
Parsing / SearchingProblem: You want to do a flat search (i.e., a &non-recursive& one) on a folder for all files and/or folders and perform some action on each one without hard-coding each file/folder.
Solution: Use a dos-wildcard (*) and provide the first part of the path (such as %UserProfile%\Start Menu\Programs in the example. Then use the
FOR /F command (type FOR /? in cmd.exe for more info) to operate on a set of files or folders under the path you gave. You can use %%a to
refer to the file/folder name for the current iteration of the loop (you'll still need the partial path that you used in the beginning too). Note that
if you want to enter the command DIRECTLY into the prompt that you only need %a, but if you're running a batch script then you have to use %%a
Parentheses can be used to issue multiple commands, just remember that the interpreter can be picky about how you format sometimes. That's why I have
opening parentheses on the same line as the FOR, DO, and IF keywords and why I have the closing FOR "parenthesis" (?) on the same line
as the start of the DO command.
Made: September 23rd, 2008 by myself. Last Updated: NA |