Processing the contents of a text file using FOR loop

Posted February 5, 2004 by gmartin in Batch file programming

As admins, we often have to take actions against a list of things (computers, servers, file shares, etc). One great way to approach this is to put the list in a test file and use a FOR command to loop through the file and take a action against the contents.

Say we have a file full of computernames:

and we need to delete each of these computers from the domain. Using a FOR loop to profress the file is the way to go (especially if there are really 300 computer names!)

First a test:
FOR /f %a in (‘complist.txt’) do echo Computer: %a

should return
Computer: EricsPC
Computer: BobsPC
Computer: ExtraPC

To actually delete the PCs from the domain, change the command to:

FOR /f %a in (‘complist.txt’) do net computer \\%a /DEL

When we run it we’ll see
net computer \\EricsPC /DEL
net computer \\BobsPC /DEL
net computer \\ExtraPC /DEL

Of course we can use this to run any command-line against any list. In fact, we can use the FOR to run a command that would generate the file.

(Note: This is valid command-line syntax. To run in a batch file, use two percent signs (e.g. ‘%%a’ )


The Conversation

Follow the reactions below and share your own thoughts.