Processing the contents of a text file using FOR loop
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:
complist.txt:
EricsPC
BobsPC
ExtraPC
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’ )
\\Greg





Tom J said on December 11, 2008
Geza,
Very simple
here is an example with your requirements
For /f %%a in (test.txt) do echo computername = %%a>>result.txt & copy \serverfile \%%ac$folder & net send admin %%a has been updated
Oz said on December 3, 2010
To have the batch file ignore the default behaviour or space and tab delimiters, simply declare a different delimiter (one that probably won’t show up in your file…like a tilde (~), grave (`), etc).
Batch file example:
– Create a text file with embedded spaces
dir > dir.txt
– Add “BEGINNING—” and “—END” to each line. See “out.txt” for results.
for /f “delims=~” %%a in (dir.txt) do echo BEGINNING—%%a—END >> out.txt