How to edit hosts file using a batch file (check for line, add if not existing and delete if existing)?

杀马特。学长 韩版系。学妹 提交于 2019-12-21 06:18:10

问题


I have a batch script to add several lines to my hosts file to block certain websites on my computer.

I would like to use the batch script in such a way that when I run my example.bat, it first checks if the lines to add exist, and if they don't then add them. But the batch file should delete the lines in case of existing already in hosts file. In other words the batch file should toggle the presence of the lines in the hosts file.

How could this be done?

Here is what I have so far. All it does is adding the lines.

@echo off

:: 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 administrator privileges.
if not errorlevel 1 goto gotAdmin

echo Set UAC = CreateObject^("Shell.Application"^) >"%temp%\getadmin.vbs"
set params=%*
if defined params set params=%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"
::--------------------------------------

@echo off

set hostspath=%SystemRoot%\System32\drivers\etc\hosts

echo 127.0.0.1 www.example1.com >> %hostspath%
echo 127.0.0.1 www.example2.com >> %hostspath%
echo 127.0.0.1 www.example3.com >> %hostspath%

exit

回答1:


A pure batch code with explanatory comments:

@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "hostspath=%SystemRoot%\System32\drivers\etc\hosts"

rem Initialize the array of our hosts to toggle
for %%a in (
    "127.0.0.1 www.example1.com"
    "127.0.0.1 www.example2.com"
    "127.0.0.1 www.example3.com"
) do (
    set /a numhosts+=1
    set "host!numhosts!=%%~a"
)

>"%hostspath%.new" (
    rem Parse the hosts file, skipping the already present hosts from our list.
    rem Blank lines are preserved using findstr trick.
    for /f "delims=: tokens=1*" %%a in ('%SystemRoot%\System32\findstr.exe /n /r /c:".*" "%hostspath%"') do (
        set skipline=
        for /L %%h in (1,1,!numhosts!) do (
            if "%%b"=="!host%%h!" (
                set skipline=true
                set found%%h=true
                echo - %%b 1>&2
            )
        )
        if not "!skipline!"=="true" echo.%%b
    )
    for /L %%h in (1,1,!numhosts!) do (
        if not "!found%%h!"=="true" echo + !host%%h! 1>&2 & echo !host%%h!
    )
)
move /y "%hostspath%" "%hostspath%.bak" >nul || echo Can't backup %hostspath%
move /y "%hostspath%.new" "%hostspath%" >nul || echo Can't update %hostspath%
endlocal
pause


来源:https://stackoverflow.com/questions/32881762/how-to-edit-hosts-file-using-a-batch-file-check-for-line-add-if-not-existing-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!