Color changing in windows ping - windows

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

Related

Errorlevel always returns 0 in a for loop with ping command

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

How can I make text engine in cmd

I try to make text engine in cmd.
So I use this code:
#echo off
cls
echo h
cls
echo he
cls
echo hel
cls
echo hell
cls
echo hello
But when I run the file I can't see any text.
So I used another code:
#echo off
cls
echo h
goto :2
:2
cls
echo he
goto :3
:3
cls
echo hel
goto :4
:4
cls
echo hell
goto :5
:5
cls
echo hello
When I first open the file I only see the he. After that I see no text.
What did I did wrong?
I want to know why it has error and how to fix it to make text engine.
Here's an example of a windowsbatch-file which doesn't do what your example is demonstrating, but does something I think you may prefer instead:
#Set "TextString=This is my text string!"
#For /F %%G In ('"Prompt $H&For %%H In (1) Do Rem"') Do #Set "BS=%%G"
#(For /F Delims^=^ EOL^= %%G In ('(%SystemRoot%\System32\cmd.exe /D /S ^
/U /V /C "Echo=!TextString!"^) ^| %SystemRoot%\System32\find.exe /V ""'
) Do #Set /P "=.%BS%%%G" 0< NUL & %SystemRoot%\System32\PATHPING.EXE ^
127.0.0.1 -n -q 1 -p 150 1> NUL) & Echo=
#Pause
You simply place your required text to be printed, into the first line (between the = and closing "), and double-click it to run and view. If the intent is to run the script directly from cmd, you do not need the last line, #Pause, and can safely remove it.
As a result of a comment, I have decided to present the code in a slightly different way, so that it can be reused for different strings.
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F %%G In ('"Prompt $H&For %%H In (1) Do Rem"') Do Set "BS=%%G"
Set "TextString=This is my text string!"
Call :GhostTypeIt
Set "TextString=This is "another" string."
Call :GhostTypeIt
Set "TextString=This & That are <words>."
Call :GhostTypeIt
Pause
Exit /B
:GhostTypeIt
(For /F Delims^=^ EOL^= %%G In ('(%SystemRoot%\System32\cmd.exe /D /S ^
/U /V /C "Echo=!TextString!"^) ^| %SystemRoot%\System32\find.exe /V ""'
) Do Set /P "=.%BS%%%G" 0< NUL & %SystemRoot%\System32\PATHPING.EXE ^
127.0.0.1 -n -q 1 -p 150 1> NUL) & Echo=
GoTo :EOF

how to run cmd command netsh using notepad

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.

Batch file to determine websites in IE

Is there a piece of code which can be used in a batch file to determine if firstly IE is open, and if so which websites are open in the tab(s)?
I am needing to force close IE when a user locks their PC, and if a specific website is open.
Thanks in advance.
Give a try for this batch file :
#echo off
Title Checking Running Process and Get their command lines
setlocal enabledelayedexpansion
Mode 90,25 & color 0A
Set "ProcessName=iexplore.exe"
Set "String2Search=facebook"
Call :CheckRunning !ProcessName!
If /I "%flag%"=="True" (
color 0A
echo %flag%
Call :GetCommandLine !ProcessName!
echo(
Call :CheckString_in_URL "%String2Search%"
) else (
color 0C
echo %flag%
echo !ProcessName! is not running !
pause>nul & exit
)
Exit
::********************************************************************************************************
:CheckRunning <ProcessName>
Set "ProcessName=%1"
tasklist /NH /FI "imagename eq %ProcessName%" 2>nul |find /i "%ProcessName%" >nul
If not errorlevel 1 ( Set "flag=True" ) else ( Set "flag=False" )
Exit /b
::********************************************************************************************************
:GetCommandLine <ProcessName>
Set "ProcessCmd="
for /f "tokens=2 delims==" %%P in ('wmic process where caption^="%~1" get commandline /format:value ^| findstr /I "%~1" ^| find /I /V "%~nx0" 2^>nul') do (
Set "ProcessCmd=%%P"
echo !ProcessCmd!
)
Exit /b
::******************************************************************************************************
:Kill <ProcessName>
Taskkill /IM "%~1" /F>nul 2>&1
Exit /b
::******************************************************************************************************
:CheckString_in_URL <String2Search>
set "String2Search=%~1"
(
echo Set objFso = CreateObject^("Scripting.FileSystemObject"^)
echo Set colShWindows = CreateObject^("shell.application"^).Windows
echo For Each w In colShWindows
echo If objFso.GetFileName^(LCase^(w.FullName^)^) = "iexplore.exe" Then
echo WScript.Echo w.LocationURL
echo End If
echo Next
)>"%Temp%\iexplore_tabs.vbs"
setlocal EnableDelayedExpansion
for /f %%a in ('cscript //nologo "%Temp%\iexplore_tabs.vbs"') do (
set /a index+=1
set "URL[!index!]=%%a"
)
for /L %%i in (1,1,%index%) do (
echo !URL[%%i]! | find /I "%String2Search%">nul && (
echo Found this string "%String2Search%" in the URL "!URL[%%i]!"
echo(
echo Did you want to kill this process "!ProcessName!" Y/N ?
Set /p "Answer="
If /I "!Answer!"=="Y" ( Call :Kill "!ProcessName!" ) else ( exit )
) || (
echo No string like "%String2Search%" found in "!URL[%%i]!"
Timeout /T 5 /nobreak>nul
)
)
exit /b
::******************************************************************************************************
I'm grateful to aGerman that give me the idea of how to enumerate the URLs of the InternetExplorer tabs

find where or which line error is occur while running in Batch Script?

I want to know error line number where error was occure by batch script and also i want to print whole line in batch script?
set t=%date%_%time%
set x=FORD_DLCM_T6_FTC
set a="%m%\%x%"
cd /d "C:\PRQA\PRQA-Framework-2.1.2\common\bin"
qacli admin --set-license-server 5055#00.00.0.0 || goto :error
qacli admin --debug-level DEBUG || goto :error
goto :EOF
:error
set remark= %ERRORLEVEL%
set status= Failure
echo ProjectName: %x%
echo Status: %status%
echo Remark: %remark%
echo Date: %t%
echo %x%,%status%,traceback(),%t% > "C:\Test\Build.csv"
echo Failed with error #%errorlevel%.
exit /b %errorlevel%
can any one help me out?
jeb has described how the search for the right line works. in the event of an error, a call is triggered and the parameters are a unique string and an offset, which points to the number of missing lines to the correct line. Findstr looks for the unmistakable string and prints that line number. With the settlement that's right again.
I've put together some macros to show that there are other ways to read the right line.
#echo off
setlocal
set prompt=$g$s
call :setAllmacros
(call)
rem begin in echo off - what line is it please ?
%ID-1:##==rem?%
(call )
%ID-1:##==call%
set/a+
%ID-1:##==001% call :ErrorLogging Line:%%L Errorlevel:%errorlevel%
echo 2
(call) || %ID-0:##==2% call :Errorlogging Line:%%L Errorlevel:%%errorlevel%%
echo %errorlevel%
find /n || %ID-0:##==003% call :Errorlogging Line:%%L Errorlevel:%%errorlevel%%
%ID-0:##==008%
pushG 556
%ID-1:##==004% call :ErrorLogging Line:%%L Errorlevel:%errorlevel%
%Line#print%:33=="
pause
exit /b
:errorlogging
#echo on
rem %*
#echo off
exit /b
:setAllmacros
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
(set ^"lf=^
%== define LF + CR ==%
)
for /f %%i in ('copy /z "%~f0" nul') do set "CR=%%i"
rem Prints the fullline itself with LineNumber into stderr
rem usage: %Line#print%:UniqueID"
rem command || %Line#print%:01"
set "Line#print= # <"%~f0" >&2 find /n "%%Line#print%%"
rem Read the fullline BEFORE into Variables with LineNumber; do something ...
rem usage: command 1 line before
rem %ID-1:##==01% [command %%L ... %%M ...]
set ID-1= if errorlevel 1 for /f "usebackQtokens=1*delims=:" %%L in (^
`cmd /v /c ^"findstr /n /r /c:"..*^!CR^!*^!LF^!.*ID-1:.#^=^##%%" "%~f0"^"`) do ^>^&2 echo BatchLine: %%L -- %%M ^&
rem Read the fullline itself into Variables with LineNumber; do something ...
rem usage: command || %ID-0:##==01% [command %%L ... %%M ...]
set ID-0= # for /f "tokens=1*delims=:" %%L in ('findstr /n /r /c:"ID-0:.#=##%%" "%~f0"') do ^>^&2 echo BatchLine: %%L -- %%M ^&
exit /b
hope it helps
Phil

Resources