【发布时间】:2020-04-15 15:16:22
【问题描述】:
我正在尝试获取一个批处理文件来显示 ping 结果,同时记录到一个文本文件。我找到了以下解决方案:https://stackoverflow.com/a/32185695/13321999。这正是我在连接所有东西时所需要的,但是我发现如果网络断开导致“一般故障”(仅通过拔掉我的以太网电缆来模拟),命令提示符窗口/批处理文件将简单地关闭。我希望让输出看起来像这样:
Target Host = www.google.com
Pinging www.google.com [172.217.9.36] with 32 bytes of data:
Wed 04/15/2020 11:01:54 Reply from 172.217.4.196: bytes=32 time=46ms TTL=55
Wed 04/15/2020 11:01:55 Reply from 172.217.4.196: bytes=32 time=29ms TTL=55
Wed 04/15/2020 11:01:56 General failure.
Wed 04/15/2020 11:01:57 General failure.
Wed 04/15/2020 11:01:58 Reply from 172.217.4.196: bytes=32 time=29ms TTL=55
Wed 04/15/2020 11:01:59 Reply from 172.217.4.196: bytes=32 time=30ms TTL=55
Wed 04/15/2020 11:02:01 Request timed out.
Wed 04/15/2020 11:02:04 Request timed out.
Wed 04/15/2020 11:02:05 General failure.
Wed 04/15/2020 11:02:06 Reply from 172.217.4.196: bytes=32 time=31ms TTL=55
下面是我使用的代码作为参考,它是从链接的帖子中复制的。我本来只想发表评论,但我还不够酷。
echo off
set /p host=host Address:
set logfile=Log_%host%.log
echo Target Host = %host% >%logfile%
for /f "tokens=*" %%A in ('ping %host% -n 1 ') do (echo %%A>>%logfile% && GOTO Ping)
:Ping
for /f "tokens=* skip=2" %%A in ('ping %host% -n 1 ') do (
echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A>>%logfile%
echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A
timeout 1 >NUL
GOTO Ping)
有什么方法可以在批处理文件中处理这些错误以使其不会崩溃吗?
【问题讨论】:
标签: batch-file logging error-handling ping