main.bat
1 @echo off 2 color 0a 3 title hosts appender 2.0 4 5 SETLOCAL ENABLEDELAYEDEXPANSION 6 set /a RTN_VAL=0 7 set ORIGIN_HOSTS=C:\Windows\system32\drivers\etc\hosts 8 set FILE_HOSTS=hosts.tmp 9 set FOLDER_HOSTS=hosts.tmp.1 10 11 if not exist "%ORIGIN_HOSTS%" ( 12 echo Not exist hosts. 13 goto NORMAL_EXIT 14 ) 15 16 set /a RTN_VAL=0 17 cd /d "%ORIGIN_HOSTS%" && set /a RTN_VAL=1 18 if !RTN_VAL! equ 1 ( 19 echo Not a hosts file. 20 goto NORMAL_EXIT 21 ) 22 cls 23 24 if "%TEMP%" neq "" ( 25 cd /d "%TEMP%" 26 set /a RTN_VAL=0 27 cd . > "%FILE_HOSTS%" || set /a RTN_VAL=1 28 if !RTN_VAL! equ 1 ( 29 cls 30 echo Can not access to "%FILE_HOSTS%". 31 goto NORMAL_EXIT 32 ) 33 ) else ( 34 echo Environment Variables - TEMP is empty. 35 goto NORMAL_EXIT 36 ) 37 38 :INPUT_COMMENTS 39 set /p COMMENTS=Enter comments: 40 if "%COMMENTS%" equ "" ( 41 goto INPUT_COMMENTS 42 ) 43 :INPUT_IP_ADDRESS 44 set /p IP_ADDRESS=Enter IP address: 45 if "%IP_ADDRESS%" equ "" ( 46 goto INPUT_IP_ADDRESS 47 ) 48 :INPUT_HOST_NAMES 49 set /p HOST_NAMES=Enter host names: 50 if "%HOST_NAMES%" equ "" ( 51 goto INPUT_HOST_NAMES 52 ) 53 54 >> "%FILE_HOSTS%" echo. 55 >> "%FILE_HOSTS%" echo # %COMMENTS% 56 >> "%FILE_HOSTS%" echo %IP_ADDRESS% %HOST_NAMES% 57 58 cls 59 echo Preview: 60 type "%FILE_HOSTS%" 61 echo. 62 63 choice /c "Yn" /cs /m "Do you want to append?" 64 if %ERRORLEVEL% equ 1 ( 65 set /a RTN_VAL=0 66 type "%FILE_HOSTS%" >> "%ORIGIN_HOSTS%" || set /a RTN_VAL=1 67 if !RTN_VAL! equ 0 ( 68 echo Completed successfully. 69 goto NORMAL_EXIT 70 ) else ( 71 cls 72 if exist "%FOLDER_HOSTS%" ( 73 rmdir /s /q "%FOLDER_HOSTS%" 74 ) 75 mkdir "%FOLDER_HOSTS%" 76 type "%ORIGIN_HOSTS%" > "%FOLDER_HOSTS%\hosts" 77 type "%FILE_HOSTS%" >> "%FOLDER_HOSTS%\hosts" 78 79 set ORIGIN_ATTR= 80 for /f "tokens=*" %%I in ("%ORIGIN_HOSTS%") do ( 81 set ORIGIN_ATTR=%%~aI 82 ) 83 if "!ORIGIN_ATTR!" neq "" ( 84 set /a RTN_VAL=0 85 for /f "tokens=1* delims=-" %%m in ("!ORIGIN_ATTR!") do ( 86 set ORIGIN_ATTR=%%m 87 set /a RTN_VAL=1 88 ) 89 if !RTN_VAL! equ 0 ( 90 set ORIGIN_ATTR= 91 ) 92 ) else ( 93 echo Can not obtain file attributes. 94 goto NORMAL_EXIT 95 ) 96 attrib -r -a -s -h -i "%FOLDER_HOSTS%\hosts" 97 set SURPLUS=!ORIGIN_ATTR! 98 set STR_ATTR= 99 :PROCESS_ATTR 100 for /f "tokens=*" %%m in ("!SURPLUS!") do ( 101 set STR_ATTR=!STR_ATTR!+!SURPLUS:~0,1! 102 set SURPLUS=!SURPLUS:~1! 103 ) 104 if "!SURPLUS!" neq "" ( 105 goto PROCESS_ATTR 106 ) 107 if "!STR_ATTR!" neq "" ( 108 rem No 'I'. 109 attrib !STR_ATTR!"%FOLDER_HOSTS%\hosts" 110 ) 111 112 set /a RTN_VAL=0 113 xcopy /y /q /h /r /k "%FOLDER_HOSTS%\hosts" "%ORIGIN_HOSTS%" || set /a RTN_VAL=1 114 if !RTN_VAL! equ 0 ( 115 cls 116 echo Completed successfully. 117 goto NORMAL_EXIT 118 ) else ( 119 echo Failed. 120 goto NORMAL_EXIT 121 ) 122 ) 123 ) 124 echo. Goodbye. 125 126 :NORMAL_EXIT 127 pause 128 exit