OK thanks for all information , I change my CVS in :
NUMBER;CITY;SERVER;NUMBER1;NUMBER2;EMAIL;ADDRESS
3;3 - NEW YORK;192.168.1.10;32049586848;032059684749;pippo#vision.de;Mießtaler Straße 12 A-9020 Klagenfurt
4;4 - Rome;192.168.1.22;345689768;0234567890;pluto#vision.uk;Via Platani 00133 22 Rome
and I changed the code like this :
#echo off
cls
setlocal enabledelayedexpansion
set CSVFILE=test.csv
:HOME
cls
set column=""
echo TEST
echo 1 Search IP
echo X Close
echo.
Choice /C 1X /N /M "Please make a selection: "
echo.
IF ERRORLEVEL 2 GOTO :EXIT
IF ERRORLEVEL 1 GOTO :IP
:IP
set column=SERVER
echo ---- Enter IP ----
set /p strsearch=
cls
GOTO :FINDIT
:FINDIT
for /f "skip=1 tokens=*" %%A in (%CSVFILE%) do (
set inline=%%A
for /f "tokens=1-7 delims=;" %%1 in ("!SERVER!") do (
set "NUMBER=%%~1" & set "CITY=%%~2" & set "SERVER=%%~3" & set "ADDRESS=%%~7"
if /I "!%column%!" equ "%strsearch%" GOTO :SHOW
)
)
:NFOUND
echo NOT FOUND Try AGAIN
pause
GOTO :HOME
:SHOW
echo SERVER: %SERVER%
echo Number: %NUMBER%
echo City: %CITY%
echo Address: %ADDRESS%
pause
GOTO :Home
:EXIT
Should it work now? What do you think about it ?
I can use csv files and bat files, i cannot use power shell on this system.
I have a file CSV :
NCITY;SERVER;NUMBER1;NUMBER2;EMAIL;ADDRESS
3 - NEW YORK;192.168.1.10;32049586848;032059684749;pippo#vision.de;Mießtaler Straße 12 A-9020 Klagenfurt
4 - Rome;192.168.1.22;345689768;0234567890;pluto#vision.uk;Via Platani 00133 22 Rome
I would like to create a bat file that, given an IP, shows me the corresponding number, name and address on the screen.
I was thinking of using this as a base script:
#echo off
cls
setlocal enabledelayedexpansion
set CSVFILE=test.csv
:HOME
cls
set column=""
echo TEST
echo 1 Search IP
echo X Close
echo.
Choice /C 1X /N /M "Please make a selection: "
echo.
IF ERRORLEVEL 2 GOTO :EXIT
IF ERRORLEVEL 1 GOTO :IP
:IP
set column=SERVER
echo ---- Enter IP ----
set /p strsearch=
cls
GOTO :FINDIT
:FINDIT
for /f "skip=1 tokens=*" %%A in (%CSVFILE%) do (
set inline=%%A
for /f "tokens=1-5 delims=," %%1 in ("!SERVER!") do (
set "SERVER=%%~1" & set "fname=%%~2" & set "comp=%%3" & set "cit=%%4" & set "stat=%%5"
if /I "!%column%!" equ "%strsearch%" GOTO :SHOW
)
)
:NFOUND
echo NOT FOUND Try AGAIN
pause
GOTO :HOME
:SHOW
echo SERVER: %SERVER%
echo Number: %lname%,%fname%
echo City: %cit%
echo Address: %stat%
pause
GOTO :Home
:EXIT
Can you help me fix it?
I haven't used bat files for a long time
thanks
Ok. So, you can't use PowerShell. Perhaps you should wonder why? Please do not consider this an answer for your question. However, someone else might benefit from it.
Using PowerShell for interactive console apps is a bit of underkill for PowerShell's capabilities. But, it can do it. And, it is already on your supported Windows system; nothing additional to install.
Save this in a file named Find-FromServerCsv.ps1
Run it in a PowerShell console using .\Find-FromServerCsv
Run it in a cmd.exe console using powershell -NoLogo -NoProfile -File ".\Find-FromServerCSV.ps1"
[CmdletBinding()]
Param()
$CsvFile = '.\csvpick.txt'
$Title = "Welcome"
$Info = "Just to Demo Promt for Choice"
$options = [System.Management.Automation.Host.ChoiceDescription[]] #('&Search by IP', '&Exit')
[int]$defaultchoice = 1
$opt = $host.UI.PromptForChoice($Title , $Info , $Options,$defaultchoice)
switch($opt) {
0 {
Write-Verbose 'doing search by IP'
$IpAddress = Read-Host -Prompt 'Please enter the IP address: '
Import-Csv -Path $CsvFile -Delimiter ';' |
Where-Object { $_.SERVER -eq $IpAddress } |
Select-Object -Property NUMBER1,NCITY,ADDRESS
}
1 {
Write-Verbose 'doing exit'
}
}
Related
I am trying to create a batch script that will ping a machine by hostname, save ip and domain to a variable and display the state (ON or OFF).
How can i fix this code so it will display the status correctly?
My code always returns ON even if pc is actually OFF.
#echo off
setlocal ENABLEDELAYEDEXPANSION
set hostname=non-existent-hostname
set domain=UNRESOLVED
set ip=UNRESOLVED
for /f "tokens=2,3 delims= " %%b in ('ping -a -4 -n 1 !hostname! ^| find "Pinging"') do (
set domain=%%b
set ip=%%c
)
if errorlevel 1 (
echo !hostname! !ip! [!domain!] is OFF
) else (
echo !hostname! !ip! [!domain!] is ON
)
pause
I have another approach using this kind of ping, because my machine is French.
For example, this batch script pings a list of URLs and displays their status (ON/OFF) with different colors.
The URLs are defined in the "URLS" variable.
The script loops through the URLs, formats them using a StringFormat function, gets the IP address of each URL using the "ping" command, and then displays the status of each URL (ON or OFF) with a color using a PSColor function.
#echo off
Title Multi-Ping hosts with colors
Set URLS="non-existent-hostname","https://www.google.com","Nothingtotest","https://www.yahoo.com","www.reddit.com",^
"http://www.wikipedia.com","www.stackoverflow.com","www.bing.com","NoBodyHere.com"
setlocal ENABLEDELAYEDEXPANSION
for %%a in (%URLS%) do (
Call :StringFormat "%%~a"
set "ip="
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 !URL!') do set "ip=%%b"
ping -n 1 !URL!>nul && set "msg=!URL! - !ip! ON" && Call :PSColor "!msg!" Green \n || set "msg=!URL! - !ip! OFF" && Call :PSColor "!msg!" Red \n
)
pause & Exit
::---------------------------------------------------------------------------------
:StringFormat <URL>
(
echo Function StringReplace(Str^)
echo Str = Replace(Str,"http://",""^)
echo Str = Replace(Str,"https://",""^)
echo StringReplace = str
echo End Function
echo wscript.echo StringReplace("%~1"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "URL=%%~a" )
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::---------------------------------------------------------------------------------
:PSColor <String> <Color> <NewLine>
If /I [%3] EQU [\n] (
Powershell Write-Host "`0%~1" -ForegroundColor %2
) Else (
Powershell Write-Host "`0%~1" -ForegroundColor %2 -NoNewLine
)
Exit /B
::---------------------------------------------------------------------------------
I figured it out, thanks everyone for hints.
#echo off
setlocal ENABLEDELAYEDEXPANSION
set hostname=non-existent-hostname
set domain=UNRESOLVED
set ip=UNRESOLVED
for /f "tokens=2,3 delims= " %%b in ('ping -a -4 -n 1 !hostname! ^| find "Pinging"') do (
set domain=%%b
set ip=%%c
)
ping -n 1 %hostname% >nul
if %errorlevel% == 0 (
echo %hostname% %ip% [%domain%] is ON
) else (
echo %hostname% %ip% [%domain%] is OFF
)
pause
Does anyone know how to make windows pinger (.bat) to show normally green but when and only when the target of the ping is offline the color is red? I have tried this several times and never got it to work. The current script is down below. That one does not work it will just change colord rapidly.
:top
PING -n 1 %IP% | FIND "TTL="
IF ERRORLEVEL 1 (SET in=0b & color 04 & echo Connection timed out.)
IF NOT ERRORLEVEL 1 GOTO color
REM errorhandling, errorlevel >= 1
ping -t 2 0 10 127.0.0.1 >nul
GoTo top
:color
color 02
GoTo top```
Here is an example for testing :
#echo off
REM https://pastebin.com/zjYwSqUM
Title Multi-Ping hosts Tester with colors updated on 2021 by Hackoo
call :init
set "URLS=%~dp0URLS.txt"
If Not exist "%URLS%" goto CreateDummyFile
mode con cols=70 lines=35
set "LogFile=PingResults.txt"
If exist "%LogFile%" Del "%LogFile%"
echo(
call :color 0E " ------- Ping status of targets hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
Call :StringFormat "%%a"
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 !URL!') do set "ip=%%b"
ping -n 1 !URL!>nul && set "msg=!URL! - !ip! ALive ok" && Call :Color 0A " !msg!" 1 || set "msg=!URL! - !ip! Dead failed to respond" && Call :Color 0C " !msg!" 1
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" "%LogFile%" & TimeOut /T 5 /Nobreak>nul & exit
::*************************************************************************************
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::*************************************************************************************
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::*************************************************************************************
:ReplaceString <Data> <String1> <String2>
(
echo Wscript.echo Replace("%~1","%~2","%~3"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "URL=%%a" )
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::*************************************************************************************
:StringFormat <URL>
(
echo Function StringReplace(Str^)
echo Str = Replace(Str,"http://",""^)
echo Str = Replace(Str,"https://",""^)
echo StringReplace = str
echo End Function
echo wscript.echo StringReplace("%~1"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "URL=%%a" )
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::*************************************************************************************
:CreateDummyFile
(
echo http://www.hyperdebrid.com
echo http://www.fakirdebrid.net
echo http://www.keepfiles.fr
echo http://www.4shared.com
echo https://1fichier.com
echo http://www.mega.co.nz
echo http://www.mediafire.com
echo http://www.uploaded.net
echo http://www.oboom.com
echo http://www.letitbit.net
echo http://www.keep2share.cc
echo http://alfafile.net
echo https://www.bigfile.to
echo http://www.dailymotion.com
echo http://www.datafile.com
echo http://www.Depfile.com
echo http://www.Dropbox.com
echo http://www.Extmatrix.com
echo http://www.Fboom.me
echo http://www.Filefactory.com
echo http://www.Filesmonster.com
echo http://www.Fshare.vn
echo http://www.Keep2share.com
echo http://www.Mega.nz
echo http://www.Rapidgator.net
echo http://www.Scribd.com
echo http://www.Soundcloud.com
echo http://www.Speedyshare.com
echo http://www.Turbobit.net
echo http://www.Vimeo.com
)>%URLS%
start /b "" cmd /c "%~f0" & exit
::*************************************************************************************
EDIT : on 22/01/2021 # 12:53
#echo off
Title IP Pinger with color by Hackoo 2021
:Main
cls & echo(
echo Type the IP address for checking
Set /P "IP="
call :init
Setlocal EnableDelayedExpansion
ping -n 1 !IP! |find /I "TTL">nul && set "msg=!IP! - ALive ok" && (
Call :Color 0A "!msg!" 1
) || (
set "msg=!IP! - Dead - Failed to respond" && Call :Color 0C "!msg!" 1
)
echo(
echo Hit any key to check another IP address !
Pause>nul & goto Main
::------------------------------------------------------------------------------------
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::------------------------------------------------------------------------------------
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::------------------------------------------------------------------------------------
Achieved with the below
cls
echo off
:top
PING -n 1 %1 | FIND "TTL="
IF ERRORLEVEL 1 (
SET in=0b
color 04
echo Connection timed out.
GOTO top
) else (
GOTO color
)
GoTo top
:color
color 02
ping 127.0.0.1 -n 2 > nul
GoTo top
Theres many approaches you can take for this task
The two main components of the task are:
effecting a means of conditional execution based on success or failure.
&& can be used to execute a command if the previous command on the same line was succesful.
|| Can be used to execute a command if the previous command failed / did not execute.
Coloring text output
Findstr can be used to read a filename and display it using hex color values. This can be used for printing strings by creating filenames with text matching the string you wish to output, provided the characters in the string aren't invalid for use in filenames.
Here's an example that uses these two main points to effect the desired output:
#Echo off
rem /* Macro Definitions */
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
rem /* %\C% - Color macro; No error checking. Usage:
::: %\C:?=HEXVALUE%Output String
::: Concatenated: (%\C:?=HEXVALUE%Output String) & (%\C:?=HEXVALUE%Output String)
::: Concatenated during conditional execution: ((%\C:?=HEXVALUE%Output String) & (%\C:?=HEXVALUE%Output String))
rem To force a new line; terminate an output string with \n */
Set "\C=For %%o in (1 2)Do if %%o==2 (( <nul set /p ".=%DEL%" > "^^!os:\n=^^!" ) & ( findstr /v /a:? /R "^$" "^^!os:\n=^^!" nul ) & ( del "^^!os:\n=^^!" > nul 2>&1 ) & (If not "^^!os:\n=^^!" == "^^!os^^!" (Echo/)))Else Set os="
rem /* Ensure macro escaping is correct depending on delayedexpansion environment type */
If Not "!![" == "[" (
Set "\C=%\C:^^=^%"
)
::: SCRIPT MAIN BODY
Setlocal EnableExtensions EnableDelayedExpansion
PUSHD "%~dp0"
ping -n 1 www.google.com | find "TTL" > nul && ((%\C:?=20%www.google.com)&(%\C:?=02% online\n)) || ((%\C:?=40%www.google.com)&(%\C:?=04% offline\n))
ping -n 1 www.googlefalse.com | find "TTL" > nul && ((%\C:?=20%www.googlefalse.com)&(%\C:?=02% online\n)) || ((%\C:?=40%www.googlefalse.com)&(%\C:?=04% offline\n))
POPD
Endlocal
Goto :Eof
I want to make autorun .bat program that automatically performs netsh cmd and save the result in .txt file by the just simple click of a button.
below is what I wrote in notepad and saved as getkey.bat
echo netsh wlan show profile name=wifi_name key=clear >Desktop/savedpasskey.txt
exit
but it is not working
To show the password of your WIFI SSID , you must execute this batch file with admin rights :
#echo off & setlocal enabledelayedexpansion
Set "Copyright=by Hackoo 2017"
Title %~n0 %Copyright%
Mode con cols=75 lines=8
cls & color 0A & echo.
echo ***********************************************
echo %~n0 %Copyright%
echo ***********************************************
echo(
if _%1_==_Main_ goto :Main
Set Count=0
Set L=0
:getadmin
echo %~nx0 : self elevating
set vbs=%temp%\getadmin.vbs
(
echo Set UAC = CreateObject^("Shell.Application"^)
echo UAC.ShellExecute "%~s0", "Main %~sdp0 %*", "", "runas", 1
)> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
::*************************************************************************************
:Main
Call :init
Call :CountLines
Set "PasswordLog=%~dp0Wifi_Passwords_on_%ComputerName%.txt"
%Mod%
echo(
echo ***********************************************
echo %~n0 %Copyright%
echo ***********************************************
echo(
Call :Color 0E " [N][SSID] ================ Password" 1
echo(
(
echo ***********************************************
echo %~n0 %Copyright%
echo ***********************************************
echo(
echo [N][SSID] ==============^> "Password"
echo(
)>"%PasswordLog%"
for /f "skip=2 delims=: tokens=2" %%a in ('netsh wlan show profiles') do (
if not "%%a"=="" (
set "ssid=%%a"
set "ssid=!ssid:~1!"
call :Getpassword "!ssid!"
)
)
echo(
echo Done
If exist "%PasswordLog%" start "" "%PasswordLog%"
pause>nul
exit
::*************************************************************************************
:Getpassword
set "name=%1"
set "name=!name:"=!"
Set "passwd="
for /f "delims=: tokens=2" %%a in ('netsh wlan show profiles %1 key^=clear ^|find /I "Cont"') do (
set "passwd=%%a"
Set /a Count+=1
)
If defined passwd (
set passwd=!passwd:~1!
echo [!Count!][!name!] ====^> "!passwd!"
echo [!Count!][!name!] ====^> "!passwd!" >> "%PasswordLog%"
) else (
Set /a Count+=1
call :color 0C " [!Count!][!name!] The Password is empty" 1
echo [!Count!][!name!] The Password is empty >> "%PasswordLog%"
)
exit /b
::*************************************************************************************
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::*************************************************************************************
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::*************************************************************************************
:CountLines
for /f "skip=2 delims=: tokens=2" %%a in ('netsh wlan show profiles') do (
if not "%%a"=="" (
set /a L+=1
)
)
set /a L=!L! + 10
Set Mod=Mode con cols=75 Lines=!L!
exit /b
::*************************************************************************************
This works. You can change the TEMPFILE to wherever you want the file to be created.
SET "TEMPFILE=%USERPROFILE%\Desktop\savedpasskey.txt"
netsh wlan show profile name=wifi_name key=clear >"%TEMPFILE%"
TYPE "%TEMPFILE%"
It was not working because the path you specified to save your output text file was not getting recognized. The below code should work properly.
#echo off
netsh wlan show profile name=wifi_name key=clear >%USERPROFILE%\Desktop\savedpasskey.txt
#pause
It's always better to specify fully qualified path for the files. In this case it will be C:\Users\<User_Name>\Desktop\savedpasskey.txt where %USERPROFILE% will been replaced with C:\Users\<User_Name>.
Remove #pause if you don't want the command prompt to stay on screen after command is executed.
I am trouble shooting multiple computers with a software that is doing touch calibration. The software is creating .jpg files that I need to copy and analyze, however different users have installed the software in different locations making it tidius to search for files. Example on a file would be 002CAL000211.jpg.
I would like to create a batch file that can do the following:
Search entire C: drive with (subfolders) and automatically copy specific files to a set directory based on the the following criteria:
Filename contains the name "CAL"
Filetype is ".jpg"
Preferably I would like the files to be copied to the root of a mounted USB drive.
Any help would be highly appreciated!
Thanks!
Try this batch script :
#echo off
Title Searching for a specific file (name and type) and copy to USB Drive
Mode con cols=90 lines=10 & color 9E
setlocal ENABLEDELAYEDEXPANSION
for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=2" ^|find /i ":"') do (Set MyUSB=%%i)
set _drive=%MyUSB%
If defined _drive (
cls
echo.
echo ---------------------------------------------------------
echo Your usb key is connected as !_drive!
echo ---------------------------------------------------------
echo.
pause
Goto :search
) ELSE (
cls
color 0C
echo.
echo --------------------------------------------------------------------------
echo Your usb key is not detected, please check it and re-run again this script
echo --------------------------------------------------------------------------
echo.
)
pause
exit
:Search
Cls
echo(
echo --------------------------------------------------------------------------
echo Please Wait a while ....... Searching is in progress .........
echo --------------------------------------------------------------------------
set "LogSearch=%~dp0%~n0.txt"
set Pattern="*CAL*.jpg"
Where /R C:\ "%Pattern%" /F >"%LogSearch%" 2>&1
If "%ErrorLevel%"=="1" (
Cls
echo(
echo --------------------------------------------------------------------------
#echo No file found with this Pattern
echo --------------------------------------------------------------------------
) else (
for /f "delims=" %%a in ('Type "%LogSearch%"') do (
#echo found %%a
#Copy %%a !_drive!\
)
)
pause & exit
EDIT : 16/03/2017 #20:00
#echo off
Title Searching for a specific file (name and type) and copy to USB Drive
Mode con cols=90 lines=10 & color 9E
setlocal ENABLEDELAYEDEXPANSION
for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=2" ^|find /i ":"') do (Set MyUSB=%%i)
set _drive=%MyUSB%
If defined _drive (
cls
echo.
echo ---------------------------------------------------------
echo Your usb key is connected as !_drive!
echo ---------------------------------------------------------
echo.
pause
Goto :search
) ELSE (
cls
color 0C
echo.
echo --------------------------------------------------------------------------
echo Your usb key is not detected, please check it and re-run again this script
echo --------------------------------------------------------------------------
echo.
)
pause
exit
:Search
Cls
echo(
echo --------------------------------------------------------------------------
echo Please Wait a while ....... Searching is in progress .........
echo --------------------------------------------------------------------------
set "LogSearch=%~dp0%~n0.txt"
If exist "%LogSearch%" Del "%LogSearch%"
set Pattern="CAL" "ERROR"
For %%P in (%Pattern%) Do (
Where /R C:\ "*%%~P*.jpg" /F >> "%LogSearch%" 2>&1
If "%ErrorLevel%"=="1" (
Cls
echo(
echo --------------------------------------------------------------------------
echo No file(s^) found with this Pattern
echo --------------------------------------------------------------------------
) else (
for /f "delims=" %%a in ('Type "%LogSearch%"') do (
#echo found file %%a
#Copy /Y %%a !_drive!\
)
)
)
pause & exit
My internet is not always working properly and I'd like to check the quality based on the cmd windows tool. I believe it's a task simple enough for it to handle.
I've begun by making a shortcut so I can have easy access to the command:
C:\Windows\System32\PING.EXE 8.8.8.8 -t
Now I was trying to transform the cmd ping command into a visually responsive one based on the output. I'd like to make the color change according to the time response.
After looking and not finding anything related, I believe it's either impossible or no one has ever tried.
Thank you very much :)
PD: (In case there was anything unclear just ask and I'll gladly answer)
Based on Magoo's post, I wrote this little batch program.
It asks for the target, the number of requests to make, the max time allowed and the time between requests and then prints in red if the request is over the time max, otherwise it sums the number of requests. It includes timestamp to be more accurate.
Copy and paste in a text file and name it with extension ".bat" (But don't name it "ping.bat" otherwise the program will enter in an infinite loop).
REM CMD PING TOOL
REM By Daweb
REM https://stackoverflow.com/users/3779294/daweb
#ECHO OFF
REM Needed for Line colored
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=1,2 delims=#" %%a IN ('"PROMPT #$H#$E# & echo on & for %%b in (1) do rem"') do (
SET "DEL=%%a"
)
for /f %%a in ('copy /Z "%~f0" nul') do set "CR=%%a"
ECHO *****************
ECHO * CMD PING TOOL *
ECHO *****************
REM Start
:start
ECHO.
ECHO Set yours values
REM SET Target
SET /p hostInput=" - Target (ip or hostname): "
If "%hostInput%"=="" ECHO.&GOTO start
REM SET loops
SET /p loopsInput=" - Requests number: "
SET /a loops=loopsInput
REM SET time limit
SET /p maxmsInput=" - Maximum Time Limit (ms): "
SET /a maxms=maxmsInput
REM Value used for sleep between loops
SET /p sleepInput=" - Delay between requests (s): "
SET /a sleepDelay=sleepInput+1
REM Variables
SET displayText=""
SET /a countRequestsOk=0
SET /a countRequestsKo=0
SET /a totalRequests=0
SET /a maxTime=0
ECHO.
ECHO START at %TIME% [target: %hostInput%, requests: %loops%, time limit: %maxms% ms, delay: %sleepInput% s]
ECHO.
REM Loop
:loop
REM Set time
FOR /f "tokens=1-3 delims=/:" %%a IN ("%TIME%") DO (SET mytime=%%ah%%bm%%cs)
REM Get ping value
FOR /f "tokens=3delims==" %%a IN ('PING -n 1 %hostInput%') DO FOR /f "delims=m" %%b IN ("%%a") DO (
SET /a timems=%%b
SET /a totalRequests+=1
REM Check result
IF !timems! GTR %maxms% ( GOTO failed ) ELSE ( GOTO success )
)
REM Request success
:success
SET /a countRequestsOk+=1
IF !timems! GTR !maxTime! ( SET /a maxTime=timems )
<nul set /P "=!countRequestsOk! requests [Max !maxTime! ms]!CR!"
GOTO next
REM Request failed
:failed
IF !countRequestsOk! GTR 0 ECHO.
SET /a countRequestsOk=0
SET /a countRequestsKo+=1
SET displayText=" %mytime% - !timems!ms"
CALL :ColorText 0c !displayText!
GOTO next
REM Next loop
:next
REM Sleep a little bit
IF %sleepDelay% GTR 1 ( ping -n %sleepDelay% localhost > nul )
REM Check continue
SET /a loops-=1
IF %loops% gtr 0 GOTO loop
REM Display result
IF !countRequestsOk! GTR 0 ECHO.
ECHO.
ECHO STOP at %TIME%
ECHO.
if !countRequestsKo! GTR 0 (
SET displayText="FAILED - !countRequestsKo! requests over %maxms% ms on !totalRequests! requests in total"
CALL :ColorText 0c !displayText!
) ELSE (
SET displayText="SUCCESS - No request over %maxms% ms on !totalRequests! requests in total"
CALL :ColorText 02 !displayText!
)
REM Ask if restart
ECHO.&ECHO *********************
SET /p restartInput="Do it again ? (Y/N): "
If "%restartInput%"=="" ECHO *********************&GOTO start
If /I "%restartInput%"=="y" ECHO *********************&GOTO start
If /I "%restartInput%"=="n" ECHO *********************&GOTO end
REM End
:end
PAUSE
GOTO :EOF
REM Line color
:ColorText
ECHO off
ECHO %DEL% > "%~2"
FINDSTR /v /a:%1 /R "^$" "%~2" NUL
DEL "%~2" > NUL 2>&1
#ECHO OFF
SETLOCAL
SET loops=10
:loop
FOR /f "tokens=3delims==" %%a IN ('PING 8.8.8.8 -n 1') DO FOR /f "delims=m" %%b IN ("%%a") DO ECHO %%b&COLOR %%b&GOTO cchgd
:cchgd
PAUSE
SET /a loops-=1
IF %loops% gtr 0 GOTO loop
COLOR
GOTO :EOF
A simple demonstration - repeats the ping 10 times, changing colours depending on the response. Manipulate to do as you wish...
I am not sure that I know what the desired output should be, but this will output GREEN text for response times 0-39 ms, YELLOW for 40-79 ms, and RED for 80+ ms.
Run this from a cmd.exe prompt using the following command or put it into a .bat file script. Change the directory to the location where the Get-PingColor.ps1 file is landed.
powershell -NoLogo -NoProfile -File "%USERPROFILE%\bin\Get-PingColor.ps1"
=== Get-PingColor.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string[]]$ComputerNames
,[Parameter(Mandatory=$false)]
[int]$Count = 4
,[Parameter(Mandatory=$false)]
[int]$SpeedMinimumSlow = 80
,[Parameter(Mandatory=$false)]
[int]$SpeedMinimumMedium = 40
)
foreach ($ComputerName in $ComputerNames) {
$Pings = Test-Connection -ComputerName $ComputerName -Count $Count
$Average = ($Pings | Measure-Object -Property responsetime -Average).Average
$ForegroundColor = 'Green'
if ($Average -ge $SpeedMinimumSlow) { $ForegroundColor = 'Red'}
else { if ($Average -ge $SpeedMinimumMedium) { $ForegroundColor = 'Yellow' }}
Write-Host -ForegroundColor $ForegroundColor -BackgroundColor 'Black' "$ComputerName $Average ms"
}
=== Execution examples
I am loathe to put images into a post, but I do not see a way to produce color on SO.