i want to check with a simple batch script, if a Computer is pingable or not. In some case, i misstype and the hostname is incorrect, but as a feedback comes "Successful".
@echo off
REM stor.bat:
ping -n 1 %1 | find "TTL=" >nul
if errorlevel 1 (
echo Reachable
explorer.exe \\%1\c$\
) else (
echo Not reachable
)
CodePudding user response:
your command is based on find "TTL=" which works for ip4 numbers so this should work
@echo off
REM stor.bat:
ping -n 1 %1 | find "TTL="
if %errorlevel%==0 (echo Reachable & explorer.exe \\%1\c$\) else (echo Not reachable & pause)
so
stor 127.0.0.1
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reachable
but ping is not ideal with names see this response where success is not shown
stor advent
Not reachable
however ping -n 1 advent
returns no hint of "TTL"
Pinging ADVENT [fe80::6467:ace9:6aef:cb1a] with 32 bytes of data:
Reply from fe80::6467:ace9:6aef:cb1a: time=1ms
Ping statistics for fe80::6467:ace9:6aef:cb1a:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 1ms, Maximum = 1ms, Average = 1ms
one method is "Find" something in response like "round trip"
@echo off
REM stor.bat:
ping -n 1 %1 | find "round trip"
if %errorlevel%==0 (echo Reachable & explorer.exe \\%1\c$\) else (echo Not reachable & pause)
[Edit] as reminded by @Stephen we can use your first method by adding -4 to force The TTL=
@echo off
REM stor.bat:
ping -4 -n 1 %1 | find "TTL="
if %errorlevel%==0 (echo Reachable & explorer.exe \\%1\c$\) else (echo Not reachable & pause)
CodePudding user response:
This batch-file
will ping the host to identify if it is available. This uses PowerShell Core. If you are only using Windows PowerShell, change pwsh.exe
to powershell.exe
.
Remember that some hosts may have ICMP (ping) disabled.
Also, if you mistype a hostname that is online (host02 instead of host01), it will also return as successful.
SET "THEHOST=%1"
FOR /F "delims=" %%A IN ('pwsh.exe -NoLogo -NoProfile -Command ^
"if (Test-Connection -TargetName %THEHOST% -Count 1 -Quiet) { 1 } else { 0 }"') DO (
SET /A "ISCONNECTED=%%A"
)
IF %ISCONNECTED% EQU 1 (
ECHO The %THEHOST% is connected
) ELSE (
ECHO The %THEHOST% is NOT connected
)