首页 > 解决方案 > 批处理文件循环

问题描述

我正在创建一个小批处理文件来自动化我们每天使用的一些网络故障排除命令。

我创建了一个简单的菜单,但是当我尝试运行循环命令时,它会出错并且不会完成循环。选项 1 (SURVEY) 运行良好,但 PINGER 部分只是杀死命令提示符而不做任何事情。

SET /P M=Type 1, 2, 3, or 4 then press ENTER:
IF %M%==1 GOTO SURVEY
IF %M%==2 GOTO PINGER
IF %M%==3 GOTO MAP
IF %M%==4 GOTO EOF

:SURVEY
echo 3 Point WiFi Survey... Please Wait...
echo ===================================================================================================== >> surveyresults.txt
echo 3 Point WiFi Survey Results >> surveyresults.txt
netsh wlan show networks bssid >> surveyresults.txt
echo 3 Point WiFi Survey Complete
echo ===================================================================================================== >> surveyresults.txt 
GOTO MENU

:PINGER
echo Pinging Devices on Subnet... Please Wait...
echo ===================================================================================================== >> surveyresults.txt 
echo Device Pings >> surveyresults.txt
FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.1.%i | FIND /i "Reply" >> surveyresults.txt
echo Pinging Complete
echo ===================================================================================================== >> surveyresults.txt 
GOTO MENU

:EOF

标签: batch-file

解决方案


您的脚本有两个主要问题。

  1. SET /P对已知菜单条目列表的用户输入使用了错误的命令。您应该使用该CHOICE实用程序。打开命令提示符窗口类型choice /?并按下该ENTER键以查看其使用信息。

  2. 您还没有阅读该FOR命令的帮助信息for /?,其中明确指出To use the FOR command in a batch program, specify %%variable instead of %variable

因此,这是对您提交所有内容的改进重写:

%SystemRoot%\System32\choice.exe /C 1234
If ErrorLevel 4 GoTo :EOF
If ErrorLevel 3 GoTo MAP
If ErrorLevel 2 GoTo PINGER

:SURVEY
(   Echo 3 Point WiFi Survey... Please Wait... > CON
    Echo =====================================================================================================
    Echo 3 Point WiFi Survey Results
    %SystemRoot%\System32\netsh.exe WLAN Show Networks BSSID
    Echo 3 Point WiFi Survey Complete > CON
    Echo =====================================================================================================
) >> "surveyresults.txt" 
GoTo MENU

:PINGER
(   Echo Pinging Devices on Subnet... Please Wait... > CON
    Echo =====================================================================================================
    Echo Device Pings
    For /L %%G In (1,1,254) Do %SystemRoot%\System32\PING.EXE -a -n 1 192.168.1.%%G | %SystemRoot%\System32\find.exe /i "Reply"
    Echo Pinging Complete > CON
    Echo =====================================================================================================
) >> "surveyresults.txt" 
GoTo MENU

推荐阅读