【发布时间】:2018-12-24 19:37:08
【问题描述】:
我正在尝试通过 windows 批处理脚本 使用 ping 命令检查 n 千个 IP 列表中的响应,并将所有结果保存在一个文件中(是 如果响应,no 如果不响应)。这甚至可以通过批处理脚本实现吗?当我使用下面打印的脚本 (pingingN.bat) 时,我只会得到第一个 IP 答案。
@ECHO OFF
SET ServerList="C:\MyPath\ip.txt"
SET LogFile="C:\MyPath\PingResults.txt"
IF EXISTS %LogFile% DEL %LogFile%
FOR %%a IN (%ServerList%) DO (
ping -n 1 %%a | find "TTL=" > NUL
IF %ERRORLEVEL% NEQ 0 (
echo no >> %LogFile%
) ELSE (
echo yes >> %LogFile%
)
)
【问题讨论】:
-
回答您的问题:是的,有可能。无论如何,在您的代码中,您需要 delayed expansion 用于
ErrorLevel,以便%ErrorLevel%变为!ErrorLevel!,或者您将if %ErrorLevel% neq 0更改为if ErrorLevel 1(意思是 如果 ErrorLevel 等于或大于 1),因为ping无论如何都不会返回否定的ErrorLevel... -
另外
SET ServerList="C:\MyPath\ip.txt"应该是SET "ServerList=C:\MyPath\ip.txt",SET LogFile="C:\MyPath\PingResults.txt"应该是SET "LogFile=C:\MyPath\PingResults.txt",IF EXISTS %LogFile% DEL %LogFile%应该是IF EXIST "%LogFile%" DEL "%LogFile%"和FOR %%a IN (%ServerList%) DO (应该是FOR /F UseBackQ %%a IN ("%ServerList%") DO (。
标签: windows shell batch-file cmd scripting