Looping, incrementing batch files

I occasionally need to do brute-force scans or commands on networks or computer names and have found many occasions to use a script similar to this.  It leverages loops in windows batch files, plus the ability to create and increment variables on the fly in a batch file.  (Note: this would be placed in a text file saved as “batchname.cmd” and executed from a command line )

@echo off
set /a var=1
if %var% gtr 254 goto :END
psexec \192.168.1.%var%  <command>
set /a var+=1
goto LOOP

This leverages the psexec tool from the pstools suite.

line one, turn off useless messages echoed to the console with @echo off
line two, create a local variable “var” with an initial value of 1
line three, start a loop named “LOOP”
line four, check the variable “var” to  see if its value exceeds the desired limit (I typically want to scan all IPs from 1 to 254)
line five, run whatever you want leveraging the incremented variable
line six, add 1 to var
line seven, go back to the top
line eight, END

If you have eight computers named Computer1 – Computer8 start var at 1 with a limit of 8, execute your command targeting “computer%var%:

If you want to run something on IPs start var at 100 with a limit of 200, execute your command targeting “192/168.1.%var%”


If you have a list that is not in order or have no numbers you can a simpler version:

@echo off
if !%1!==!! goto :END
psexec \%1%  <command>
goto LOOP

This command is based off of command line parameters, execute the batch file using “batch.cmd Smith Jones Obama Simpson” and it will execute the command using each of the names in order.


This entry was posted in Computing, Scripting and tagged . Bookmark the permalink.

2 Responses to Looping, incrementing batch files

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.