首页 > 解决方案 > 更改 ping 错误消息

问题描述

我正在制作一个简单的批处理脚本来 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

我正在努力做到这一点,以便当我收到错误代码(请求超时)时,它会打印“主机没有响应”而不是通常的。但是它不起作用。

通常我的 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.

我将如何继续这样做?

PS 脚本的第二行是我在此处找到的命令,它使 CMD 窗口始终位于顶部。很有用!

标签: batch-fileping

解决方案


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

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

不要忘记实施某种“打破循环”

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


推荐阅读