views:

54

answers:

2

I have a following batch file:

:LOOP
ping %1
ping %2
goto LOOP

The above file works only with two command line parameters. How to make this work of variable number of command line parameters. For example if four command line parameters were provided at the run time, then it should ping all the four servers.

Any help appreciated

A: 

EDIT: after the comment of Johannes, I added some lines to my original solution to make it work like the original script:

This loops once over all arguments:

:loop 
if %1x==x goto :EOF
ping %1
shift
goto :LOOP

This loops endlessly:

:loop2
call :loop %*
goto :loop2

:loop 
if %1x==x goto :EOF
ping %1
shift
goto :LOOP
Doc Brown
This won't do the same. It will just loop once over every argument and then just call `ping` without arguments.
Joey
No, it will call `ping` *with* arguments (I tested it), but you are right, it does not the same as the original script, since it stops after one cycle. See my edit above.
Doc Brown
Sorry if I was unclear; I tried editing but it was too late already: I did mean that it will work fine the first iteration but after that if will do nothing useful anymore since all arguments have been `shift` ed away.
Joey
+1  A: 

The only option you have to deal with arbitrary numbers of arguments is to use shift. However, that won't work in the second iteration of your endless loop. You could solve this by first storing all addresses in an array and then iterating over said array, but there is an easier variant.

You can use %* to get a list of all arguments in a single string and simply loop over the tokens in that string:

@echo off
:loop
for %%x in (%*) do ping %%x
goto :loop

Code can also be found in my SVN repository.

Joey
Thank you for the code, it looks to be very close to what I'm looking for, however there seems to be some issue with your code. If i provide three parameters then it is pinging only the first and third IPAddress
@user: can't reproduce that here. It works fine with three arguments.
Joey