我有一个批处理文件:
:LOOP
ping %1
ping %2
goto LOOP
上述文件仅适用于两个命令行参数。如何使其适用于可变数量的命令行参数。例如,如果在运行时提供了四个命令行参数,则应对所有四个服务器进行ping测试。
感谢任何帮助。
我有一个批处理文件:
:LOOP
ping %1
ping %2
goto LOOP
shift
来处理任意数量的参数。但是,在无限循环的第二次迭代中,这种方法不起作用。你可以通过首先将所有地址存储在数组中,然后遍历该数组来解决此问题,但有一种更简单的方法。%*
获取单个字符串中所有参数的列表,并简单地循环遍历该字符串中的标记:@echo off
:loop
for %%x in (%*) do ping %%x
goto :loop
代码也可以在我的SVN存储库中找到。
FOR %%x IN (%*) DO ping %%x
@ECHO OFF
:loop_start
IF .%1==. GOTO end
ping %1
SHIFT
GOTO :loop_start
:end
C:\apps\Prod\85000026>tmp.bat 8.8.8.8 localhost 127.0.0.
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=21ms TTL=52
Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 21ms, Maximum = 21ms, Average = 21ms
Pinging MFGTESTFNTLSYS2 [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Ping statistics for ::1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
编辑:在 Johannes 的评论后,我添加了一些行来使我的原始解决方案像原始脚本一样工作:
这个循环遍历所有参数一次:
:loop
if %1x==x goto :EOF
ping %1
shift
goto :LOOP
这个循环无限地执行:
:loop2
call :loop %*
goto :loop2
:loop
if %1x==x goto :EOF
ping %1
shift
goto :LOOP
ping
。 - Joeyping
(我测试过了),但你是对的,它与原始脚本不同,因为它在一个周期后停止。请参见我的上面的编辑。 - Doc Brownshift
掉了。 - Joey