2015-10-01 225 views
2

我有一個批處理腳本來添加幾行到我的主機文件來阻止我的電腦上的某些網站。如何使用批處理文件編輯hosts文件(檢查行,如果不存在則添加,如果存在則刪除)?

我想以這樣的方式使用批處理腳本,當我運行我的example.bat時,它首先檢查要添加的行是否存在,如果它們不存在,則添加它們。但是批處理文件應該刪除hosts文件中已存在的行。換句話說,批處理文件應該切換hosts文件中行的存在。

這怎麼辦?

這是我到目前爲止。它所做的就是添加線條。

@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 

回答

3

純批次碼說明性註釋:

@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 
+0

THX。這工作完美。 – ApatheticEuphoria

+0

爲了確保套管無關緊要,我會將'如果「%% b」==「!host %% h!」'改爲'if/i「%% b」==「!host %% h !「'並在開始時重置numhosts。 – LotPings

相關問題