Change Color in Command Prompt Based on Result?

倖福魔咒の 提交于 2019-12-24 06:38:03

问题


Bit of a long stretch here.

If I want to run a continuous ping command, is it possible to have the output listed in a different color if lets say the result is beyond a certain point?

Example:

Ping result comes back with 22ms, white Ping result comes back with 300+, red

Is that at all possible? Will I need to make a batch file instead?

The script listed below works REALLY well. However, I need some additional action with it. When an IP address times out, this script does nothing. It just sits waiting for the next ping. Is there anyway to incorporate that?


回答1:


A rudimentary solution would be something along the lines of.

  @setlocal enableextensions enabledelayedexpansion
@echo off
set /p ipaddr="Enter ip or url: eg localhost or google.co.za or 192.168.0.1 "
set /p cutoff="enter minimum good reply ms: eg 300 "
set /a res = 0 - 1 
:loop
for /f "tokens=7,9" %%a in ('ping -n 1 !ipaddr!') do (
set /a res = 0 - 1 
  if "%%a"=="Average" (
  set a=%%b
  set /a res=!a:~0,-2!
  )
)

IF %res% == -1 (
  COLOR 2
  echo %ipaddr% failed to respond in time
)
IF %res% LEQ %cutoff% (
    IF %res% NEQ -1 (
        COLOR 2
        echo %ipaddr% responded in %res%ms
    )
)else (
    COLOR 4
    echo %ipaddr% responded in %res%ms
)
ping -n 3 127.0.0.1 >nul: 2>nul:
goto :loop

endlocal

Save it to a .cmd file and then just double click it



来源:https://stackoverflow.com/questions/37148086/change-color-in-command-prompt-based-on-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!