更改 ping 错误消息

Changing ping errormessage

我正在制作一个简单的批处理脚本来 ping 主机并检查它们的连接。这是我的代码:

@ECHO OFF

@powershell -ExecutionPolicy UnRestricted -Command "(Add-Type -memberDefinition \"[DllImport(\"\"user32.dll\"\")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x,int y,int cx, int xy, uint flagsw);\" -name \"Win32SetWindowPos\" -passThru )::SetWindowPos((Add-Type -memberDefinition \"[DllImport(\"\"Kernel32.dll\"\")] public static extern IntPtr GetConsoleWindow();\" -name \"Win32GetConsoleWindow\" -passThru )::GetConsoleWindow(),-1,0,0,0,0,67)"

title Ping tool
mode con: cols=50 lines=25

:PING
cls & set /p address= [*] Host to ping: 
@echo [*] Started pinging at: %time%
title Pinging %address%
if %ERRORLEVEL% == 1 echo Host didn't respond.         

ping  %address%  -t  & echo. & pause. & goto :PING

我试图做到这一点,以便当我收到一个错误代码(请求超时)时,它会打印 "Host didn't respond" 而不是通常的。然而它不起作用。

通常我的 ping 会输出这个:

[*] Host to ping: 8.8.8.8
[*] Started pinging at: 13:44:29.05

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=28ms TTL=52
Reply from 8.8.8.8: bytes=32 time=16ms TTL=52
Request timed out.
Request timed out.

但我希望它看起来像这样:

[*] Host to ping: 8.8.8.8
[*] Started pinging at: 13:44:29.05

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=28ms TTL=52
Reply from 8.8.8.8: bytes=32 time=16ms TTL=52
Host didn't respond.
Host didn't respond.

我将如何继续这样做?

P.S 脚本的第二行是我找到的命令 here,它使 CMD window 始终位于最前面。 很有用!

您可以将输出重定向到文件,测试错误级别,如果符合错误级别检查,则输入输出。

@Echo off
:ping
cls & set /p address= [*] Host to ping: 
ping %address%>output.txt
If Errorlevel 1 (Echo(Host unavailable) Else (TYPE output.txt)
pause>nul
Goto :ping

您无法在命令输出仍为 运行 时拦截它,因此 ping -t 对您不起作用。你需要 ping -n 1 循环,这样你就可以对每个 ping 包做出反应:

:loop
ping -n 1 www.google.com | find "TTL=" || echo Host didn't respond. 
goto :loop

不要忘记实施某种 "break the loop"

注意:这在您的内部网络中失败了,因为 Reply from <localhost>: Destination host unreachable.ping 响应被认为是 "Success",因为 一个答案(只是不是来自目的地)。