Advertisement
jcunews

AutoEnableDhcpOnError.bat

Sep 5th, 2023 (edited)
888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 1.79 KB | None | 0 0
  1. @echo off
  2. setlocal
  3.  
  4. rem Context: https://www.reddit.com/r/windows/comments/16anonp/apply_network_settings_and_if_failed_revert_back/
  5. rem Revision 2.
  6. rem
  7. rem https://www.reddit.com/user/jcunews1
  8. rem https://pastebin.com/u/jcunews
  9. rem https://greasyfork.org/en/users/85671-jcunews
  10.  
  11. rem === CONFIG BEGIN ===
  12.  
  13. set "DeviceName=Local Area Connection"
  14. set RemoteIpToCheck=8.8.8.8
  15. set RemoteIpToCheckTimeoutMilliseconds=3000
  16. set ErrorMaxDurationSeconds=30
  17.  
  18. rem === CONFIG END ===
  19.  
  20. >nul netsh interface ip show addresses "%DeviceName%"
  21. if errorlevel 1 (
  22.   echo Network device name "%DeviceName%" is not found.
  23.   pause
  24.   goto :eof
  25. )
  26.  
  27. set ErrorStartTimestamp=0
  28.  
  29. :check
  30.  
  31. set DhcpEnabled=0
  32. for /f "tokens=3 delims= " %%A in ('netsh interface ip show addresses "%DeviceName%" ^| find "DHCP enabled"') do if "%%A" == "Yes" set DhcpEnabled=1
  33.  
  34. if %DhcpEnabled% == 1 (
  35.  
  36.   set ErrorStartTimestamp=0
  37.   echo %time%: DHCP is enabled.
  38.   >nul timeout 1
  39.   goto check
  40.  
  41. )
  42.  
  43. echo %time%: DHCP is disabled. Checking internet access...
  44. >nul ping -n 1 -w %RemoteIpToCheckTimeoutMilliseconds% %RemoteIpToCheck%
  45.  
  46. if not errorlevel 1 (
  47.  
  48.   set ErrorStartTimestamp=0
  49.   echo %time%: Has internet access.
  50.   >nul timeout 1
  51.   goto check
  52.  
  53. )
  54.  
  55. for /f "tokens=1,2,3,4 delims=:." %%A in ("%time%") do set /a t=%%A*360000+%%B*6000+%%C*100+%%D
  56. if %ErrorStartTimestamp% == 0 set ErrorStartTimestamp=%t%
  57. if %t% lss %ErrorStartTimestamp% set /a ErrorStartTimestamp-=8640000
  58. set /a elapsed=(t-ErrorStartTimestamp)/100
  59. echo %time%: No internet access for %elapsed% seconds.
  60.  
  61. if %elapsed% lss %ErrorMaxDurationSeconds% goto check
  62.  
  63. echo %time%: Enabling DHCP...
  64. netsh interface ip set address "%DeviceName%" dhcp
  65.  
  66. if not errorlevel 1 echo %time%: DHCP has been enabled.
  67.  
  68. set ErrorStartTimestamp=0
  69. >nul timeout 1
  70. goto check
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement