我添加了这个答案,以防其他人想将主机条目集存储在格式与普通主机文件一样的 txt 文件中。这将查找 TAB 分隔符。这是基于@Rashy 和@that0n3guy 的回答。可以在 FOR 命令周围注意到差异。
@echo off
TITLE Modifying your HOSTS file
ECHO.
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END
:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims= " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
SET _host=%%B
SET _ip=%%A
SET NEWLINE=^& echo.
ECHO Adding !_ip! !_host!
REM REM ::strip out this specific line and store in tmp file
type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
REM REM ::re-add the line to it
ECHO %NEWLINE%^!_ip! !_host! >> tmp.txt
REM ::overwrite host file
copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END
:END
ECHO.
PAUSE
EXIT
示例“storedhosts.txt”(制表符分隔)
127.0.0.1 mysite.com
168.1.64.2 yoursite.com
192.1.0.1 internalsite.com