エラーをテストする前に、ping
コマンドのstderrをstdoutにリダイレクトする必要があると思います。2>&1
:loop
ping x.x.x.1 2>&1 | find /i "general failure" && (
netsh int ipv4 set address name="Local Area Connection" source=static address=X.X.X.2 mask=255.255.255.0 gateway=none
)
goto loop
失敗よりも成功をチェックする方が良いかもしれません。これはもう少し堅牢なもので、.1が死んだ場合に.2から.1に切り替える必要があります。競合する場合は.1から.2になります。
@echo off
setlocal
:: Host to ping
set primary=x.x.x.1
:: Ping with options (1 ping sent per loop, wait 500 ms for timeout)
set ping_options=-n 1 -w 500
:: Fail over after x ping failed responses
set fail_limit=5
:loop
:: Ping x.x.x.1. Test for "reply from". If success, set failures=0; otherwise, increment failures
( ping %ping_options% %primary% 2>&1 | find /i "reply from" >NUL && set failures=0 ) || set /a "failures+=1"
:: If failures >= limit, switch IP
if failures GEQ %fail_limit% call :switch
:: Pause for a second and begin again.
ping -n 2 0.0.0.0 >NUL
goto loop
:: Switch subroutine
:switch
:: Get current IPv4 address
for /f "tokens=2 delims={}," %%I in ('wmic nicconfig where ipenabled="TRUE" get ipaddress /format:list') do set IP=%%~I
:: If the last character if the current IP is 1, switch to 2 (or vice versa)
if %IP:~-1%==1 ( set other=%IP:0,-1%2 ) else set other=%IP:0,-1%1
:: Perform the switch
netsh int ipv4 set address name="Local Area Connection" source=static address=%other% mask=255.255.255.0 gateway=none