【发布时间】:2020-07-10 16:52:52
【问题描述】:
我正在制作一个简单的批处理脚本来 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.
我将如何继续这样做?
P.S 脚本的第二行是我找到的命令here,它使 CMD 窗口始终位于顶部。 很有用!
【问题讨论】:
-
如果您想要命令的错误级别,那么在命令有机会运行之前检查错误级别是没有意义的。 (同样
/t在这里没有意义,因为ping不会完成) -
对不起,我不是这个意思。我会改写这个问题。
-
您可以使用
FOR /F命令捕获 ping 输出并进行字符串替换,但最好使用可以在行编辑中执行的命令。 Windows 中确实没有任何本机流编辑器。您的选择是使用 JREPL.bat 之类的东西,可以在 Dostips.com 论坛上找到,或者下载 Windows 版本的 SED。
标签: batch-file ping