batch-fileappendadditionhosts-file

how to add new lines to windows hosts with a batch file


i know this was already discussed but i didn't find what i needed. I need to add new lines at the end of the hosts window file but, first i need to check if these lines already exist and than adding them.

I tried this:

set "list=examp.com=examp2.com=examp3.com"
SET NEWLINE=^0.0.0.0
for %%a in (%list%) do  (
   FINDSTR /I %%a %WINDIR%\system32\drivers\etc\hosts)
   IF %ERRORLEVEL% NEQ 0 (ECHO %NEWLINE% %%a>>%WINDIR%\System32\drivers\etc\hosts)
   pause

but the result in hosts is just 1 line like this:

0.0.0.0 %a

I also want to know if it's possible to change this:

set "list=examp.com=examp2.com=examp3.com"

with another code that will take variables from a txt file.


Solution

  • Your code is not quite as bad as Mofi would suggest. Although it's quite uncommon to use an equal sign as a delimiter for a for loop, it is nevertheless legal syntax. The largest two problems I see are that you're closing your for loop at the end of your findstr statement; and, assuming you fix that, %ERRORLEVEL% would need its expansion delayed. Or you could use the if errorlevel syntax of the if statement (see help if in a cmd console for full details`). Or even better, use conditional execution.

    Here's an example using conditional execution. This example also opens your HOSTS file for appending one time, rather than one time for each loop iteration -- a subtle efficiency improvement, true, but a worthwhile habit to practice when writing files with a loop. And because HOSTS by default has attributes set to prevent writing, I stored and removed the read-only / system / hidden / etc. attributes of the hosts file, appended the changes to the file, then restored the attributes back the way they were before.

    @echo off & setlocal
    
    set "hosts=%WINDIR%\system32\drivers\etc\hosts"
    set "list=examp.com=examp2.com=examp3.com"
    SET "NEWLINE=0.0.0.0"
    
    for /f "delims=" %%I in ('attrib "%hosts%"') do set "raw=%%~I"
    setlocal enabledelayedexpansion
    for /L %%I in (0,1,18) do if not "!raw:~%%I,1!"==" " set "attrs=!attrs!+!raw:~%%I,1! "
    endlocal & set "attrs=%attrs%"
    
    attrib -h -s -r -o -i -x -p -u "%hosts%"
    
    >>"%hosts%" (
        for %%a in (%list%) do (
            >NUL 2>NUL find /I "%%a" "%hosts%" || echo(%NEWLINE% %%a
        )
    )
    
    attrib %attrs% "%hosts%"