Batch File - For Loop

I will commonly write small batch files to automate tasks that are repetitive, due to this I find myself using the for loop a lot. Below are a few examples of when and where the for loop can be used effectively.

Looping through entries in a file 

This example will take a standard text file (MyTextFile.txt) and then loop through all lines until the end of the file is reached. For each of the lines the first word (represented by %%A) will be printed out to the screen and ping'ed.

FOR /F "tokens=1" %%A IN (C:\MyTextFile.txt) DO (

echo %%A

ping %%A

)

An example of the text file is simply:

COMPUTER01
COMPUTER02
COMPUTER03
COMPUTER04

By changing the tokens value, which word on a line that is used will change. By setting the value of tokens from 1 to 1,2 both the first and second words per line will be available via the parameters %%A and %%B. When using the following input file, within the loop %%A will be the computer name and %%B will be the IP address.

COMPUTER01 192.168.1.100
COMPUTER02 192.168.1.101
COMPUTER03 192.168.1.102

To ignore selected lines, i.e. lines that are actually comments use the eol parameter, the following for loop will ignore all lines that start with a colon:

FOR /F "tokens=1 eol=:" %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

 If the input file has a number of header lines that should not be included the skip parameter should be used, for following will exclude the first 3 files of the input file:

FOR /F "tokens=1 eol=: skip=3" %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

To override the default delimiters (space and tab) the delims parameter should be used. The following will ignore the space delimiter and instead delimiter by comma:

FOR /F "tokens=1 delims=," %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)