Quantcast
Channel: OSAKANA TAROのメモ帳
Viewing all articles
Browse latest Browse all 816

Windowsバッチファイルでping応答の違いで動作をかえる

$
0
0

Windowsバッチファイルで、指定IPアドレスから応答がなくなったら次の作業を実施する、という処理をやりたかったので作った。

普通にping実行時のERRORLEVELを見ればいいか、と思っていたが、試験した環境では応答があってもなくてもERRORLEVEL0だったので判別ができなかった・・・
調べたところ「otnx.jpのコマンド別/ping」に調査した結果と回避方法があったのでそれを使った。

ちなみにotnx.jpではfindで「bytes=32」を引っかけていたが、日本語環境だと「 バイト数 =32」になってしまうが、バッチには書きたくなかったので、その後ろにある「ms TTL=」の方を引っかけるようにした。

・停止待ちバッチファイル
応答がなかったら終了。
応答があったら3回繰り返す

@echo off
set COUNT=0
:error
set /a COUNT=COUNT+1
echo %COUNT%
if "%COUNT%" == "3" goto errorout
ping -n 1 IPアドレス | find "ms TTL=" > NUL
if ERRORLEVEL 1 goto notrespond
timeout /t 5  > nul
goto error
:notrespond
echo host stopped
goto end
:errorout
echo host not stop
:end

・起動待ちバッチファイル
ping応答がなかったら3回繰り返してみる

@echo off
set COUNT=0
:error
set /a COUNT=COUNT+1
if "%COUNT%" == "3" goto errorout
ping -n 1 IPアドレス | find "ms TTL=" > NUL
if ERRORLEVEL 1 goto error
echo host working
goto end
:errorout
echo host not working
:end

Viewing all articles
Browse latest Browse all 816

Trending Articles