I've long maintained that the FOR command is one of most basic commands every administrator should know. I have a short tutorial you can download at http://www.jdhitsolutions.com/tutorials.htm
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Here are some other examples on using the FOR command. Let's say you have some command line utility that will take a computer name as a parameter, such as ping, and you want to run it against a list of computers. List the computer names in a text file like servers.txt. Then open a command prompt where the file is and run:
FOR /F %x in (servers.txt) do @ping -n 1 %x
If you want to verify you have the basic syntax correct, run this:
FOR /F %x in (servers.txt) do @Echo %x
This should display each server name in the list.
If you want to save the output to a text file for any command you can use console redirection, like this:
FOR /F %x in (servers.txt) do @ping -n 1 %x >>pingresults.txt
Be sure to use >> and not > or you will only get results for the last computer in the text file.
If you want to take the FOR command and put it in a batch file, then remember to use %% instead of %. Here's a quick batch file version of the ping command example. To avoid errors, I recommend specifying the full path to the text file.
@echo off
::PINGCHECK.BAT
REM Delete pingresults.txt if it already exists so we get a new log
if Exist c:\scripts\pingresults.txt DEL c:\scripts\pingresults.txt
FOR /F %%x in (c:\scripts\servers.txt) do @ping -n 1 %%x >>c:\scripts\pingresults.txt
::END OF SCRIPT
IMPORTANT: The FOR command is only case sensitive when it comes to variables. %x is different than %X. If you run:
FOR /F %x in (servers.txt) do @Echo %X
You will not get the servers but rather %X.
Technorati Tags:
commandline
Scripting
batch file