For Loops In Windows With MS-DOS Command Prompt
Windows operating system provides MS-DOS from easily days of its creation. MS-DOS is a platform generally used as a command line. MD-DOS have a lot of features those provides programming capabilities. In this tutorial we will look
for loop which provides looping and enumeration capabilities for command line.
Help about for loop can be get like below.
$ for /?
For loop have the following syntax.
FOR %variable IN (set) DO command [command-parameters]
FORspecifies the loop
%variableused to store value for each step in the loop
IN (set)used to provide list for looping. This can be a file list, user list or anything else
DO command [command-parameters]is used to run commands for each step
Count Numbers and Print
We will start for with a simple example. We will just print a list that contains numbers from 1 to 5 . In each step one element in the list is set to variable and the variable will be printed with
$ for %i IN (1,2,3,4,5) DO echo %i
As we can see each step in the loop is run as a separate command .
Run Command For Each File
Previous example do not have any benefit for daily operations. System administrators generally wants to run a command on the multiple files accounts whit a simple way. We will print files located current directory with
$ for /F %i in ('dir /b *') do echo %i
Run Command For Each User
We can also run commands for each user. We will provide the user list because there is no practical way to generate user list in ms-dos in a convenient way. We will provide user list
ismail, jack, administrator . We will list information about these users with
net user command.
$ for %i in (ismail,jack,administrator) do net user %i
We will get all users information easily without typing one by one.
Run Command For Each Computer
We will run ping command for each IP address or hostname provided by the list. Our example IP list is
192.168.122.1 , 192.168.122.6 .
$ for %i in (192.168.122.1 , 192.168.122.66) do ping %i
Read List From File
In previous examples we have two method to generate list. One method is running command and providing the command result as a list to for loop. Other method is writing down the list elements one by one. There is another way to provide list. Lists elements can be read from file.
In this example we will read list elements from file named
We will provide the
/F in the for loop to read from file.
$ for /F %i in (hosts.txt) do ping %i
Specify Column Number In A File
There is advanced usage example with file. Provided file may have more than one column which is delimited with different delimiters. Specified columns may provided for loop as list element.
In this example we have file which holds user names and related information. This information is delimited with
, . We will provide user names by specifying related column.
$ for /F "tokens=1 delims=," %i in (users.txt) do net user %i