%variable. The %variable parameter represents an iterator variable. An iterator variable serves as a temporary container for data that you've captured in a For command. In other words, an iterator variable exists only within that particular For command. Typically, the first iterator variable is named %i; subsequent iterator variables proceed through the alphabet from that point (e.g., %j, %k). When you use iterator variables, you need to remember two conventions. First, the letter must be lowercase. Second, if you’re running the For command from the command-shell window, you use only one percent sign (e.g., %i). In a script, you must use two percent signs (%%i); otherwise, the script will fail.
in (set). In this segment, the (set) parameter represents the files or directories through which you want the For command to iterate. In the For command for the ping test, the set is (fileserv1 fileserv2 fileserv3 fileserv4 fileserv5). The For command will iterate through this set, temporarily assigning each server name to the %i variable.
Do command. In this segment, the command parameter represents the command sequence that you want to execute for each file or directory in the set. In the For command for the ping test, the command sequence is
Do @Ping -n 1 %i
Instead of specifying a server name for the Ping command’s computername parameter, you specify the %i variable. Prefixing the Ping command with the at (@) sign tells the command processor to turn off the command-echoing feature for that command. (For more information about disabling the command-echoing feature, see "Shell Scripting 101, Lesson 1.")
If you put all the segments together, the For command for the ping test looks like
For /d %i in (fileserv1 fileserv2 fileserv3 fileserv4 fileserv5) Do @Ping -n 1 %i
This For /d command produces the same result as the five lines of Ping code.
Using the For /f Command
If you have many servers to ping, listing all the servers in a set can get cumbersome. A better alternative is to put the server names in an input file. An input file is a file that provides input to a command or script. Typically, input files are text files. Figure 1 shows a sample input file. The For /d command you just created won’t work with the input file that Figure 1 shows. Instead, you need to use a different syntax:
For /f ["options"] %variable in (fileset) Do command
The /f switch lets you use the For command to parse a file’s contents. As the (fileset) parameter shows, you enclose the filename (or filenames—you can include more than one file in a set) in the parentheses. If you use serverlist.txt to provide the server names, the For command for the ping test looks like
For /f %i in (serverlist.txt) Do @Ping -n 1 %i