Continuing from last time.
If Command Extensions are enabled, the following additional forms of the FOR command are supported:
[Note that Windows 2000 and later have Command Extensions enabled by default.]
FOR /D %variable IN (set) DO command [command-parameters] If set contains wildcards, then specifies to match against directory names instead of file names.
For example, to delete every subdirectory that starts with an underscore in the current directory, you could run this on the command line: [Typo fixed 7/25 12:30 PM]
for /D %D in (_*) do rd /s/q "%D"
Note the quotes in the rd command; these are there in order to make sure that it does the right thing if a directory happens to contain spaces in its name.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters] Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree. If no directory specification is specified after /R then the current directory is assumed. If set is just a single period (.) character then it will just enumerate the directory tree.
For example, to list the path of every .h file under the current directory, you could run this on the command line [this is a contrived example, "dir /s/b *.h" would be more efficient]:
for /R %F in (*.h) do @echo %F
[I'll cover the usage of the @ character in a later post.]
Another example: to rename every .c file under the C:\Source directory to a .cpp file, you could run this on the command line:
for /R C:\Source %D in (.) do ren "%D\*.c" *.cpp
Note the quotes in the ren command; these are there in order to make sure that it does the right thing if a directory happens to contain spaces in its name.
FOR /L %variable IN (start,step,end) DO command [command-parameters] The set is a sequence of numbers from start to end, by step amount. So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would generate the sequence (5 4 3 2 1)
For example, to defragment your C: drive 5 times in a row and log the results of each one, you could run this on the command line:
for /L %N in (1,1,5) do defrag C: > defrag%N.log 2>&1
2>&1 redirects the standard error [2>] to the same place that the standard output is going [1> or just >]. I'll post on those at some later time.