【发布时间】:2014-07-25 22:56:53
【问题描述】:
我正在尝试创建一个脚本,让我可以从文本文件 ping 计算机列表并输出它们是否响应 CSV 文件。使用单台机器测试命令时,我收到正确的错误级别响应,但是当我使用 FOR 语句尝试时,每个结果都列为错误级别 0。
for /f %%g in (computers.txt) do (
ping -n 1 %%g | findstr "TTL"
if errorlevel equ 0 (
echo %%g,success >> results.csv
) else (
echo %%g,fail >> results.csv
)
)
我做错了什么?我已经尝试了上面的代码,以及来自Batch ping a list of computer names and write the results to file 的代码(它不返回任何响应)。有没有更好的方法来达到这个结果?任何帮助将不胜感激。
解决方案
for /f %%g in (computers.txt) do (
for /f "tokens=1" %%a in ('ping -n 1 %%g ^| findstr /i /c:"try" /c:"out" /c:"TTL"') do (
if %%a EQU Ping (echo.%%g,Could not find host>>results.csv)
if %%a EQU Destination (echo.%%g,Destination host unreachable>>results.csv)
if %%a EQU Request (echo.%%g,Request timed out>>results.csv)
if %%a EQU Reply (echo.%%g,Replied>>results.csv))
)
已按照 G 的回答中的说明进行了更新。谢谢你!
【问题讨论】:
-
您愿意改用powershell 吗?比传统的批处理文件更强大、更灵活。尝试在 Google 上搜索“powershell ping 程序”。可用的东西很多。
-
我没想过要用powershell,但是Test-Connection命令看起来很有用。当我回到办公室时,我会尝试一下。谢谢大卫!
标签: batch-file for-loop ping