Writing to the Hosts File

I need a MS DOS Batch file to write to the Hosts file. If there are existing entries in the Hosts file, how can I display these entries, and how can I append a new entry and how can I change an existing entry?
ben1211Asked:
Who is Participating?
 
Lee W, MVPConnect With a Mentor Technology and Business Process AdvisorCommented:
REM Display Hosts File contents
If Exist %windir%\system32\drivers\etc\hosts type %windir%\system32\drivers\etc\hosts

REM Add a New Entry
Echo 123.45.6.78    newentry.domain.com >> %windir%\system32\drivers\etc\hosts

Rem Change an Entry - rename old hosts file to hosts.DateCodeTimeCode
for /f "tokens=1,2*" %%a in (%windir%\system32\drivers\etc\hosts) Do (
    If "%%a" == "123.45.6.79" (
        Echo 123.45.6.78 %%b %%c >> %windir%\system32\drivers\etc\hosts.new
    ) Else (
        Echo %%a %%b %%c >> %windir%\system32\drivers\etc\hosts.new
    )
)
If Exist %windir%\system32\drivers\etc\hosts ren %windir%\system32\drivers\etc\hosts %windir%\system32\drivers\etc\hosts.%date:~-4%%date:~4,2%%date:~7,2%%time:~0,2%%time:~3,2    %%time:~6,2%
If Exist %windir%\system32\drivers\etc\hosts.new Ren %windir%\system32\drivers\etc\hosts.new %windir%\system32\drivers\etc\hosts
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.