Reputation: 411
I found about half a dozen (1, 2, 3 etc.) questions about how to add lines to the Windows hosts file but none of them are easy to maintain if you want to frequently update multiple lines with a single batch file in which you can just replace the old lines with your new ones as a block and delete everything else inside the hosts file.
127.0.0.1 example1.com
127.0.0.1 example2.com
127.0.0.1 example3.com
127.0.0.1 example4.com
127.0.0.1 example5.com
I was hoping you guys can tell me what I missed, where to look or maybe even give me an example. I'd really appreciate your help.
Upvotes: 0
Views: 1295
Reputation:
If you are sure you know what you are doing:
to rewrite the whole hosts file with new contents simply:
@Echo off
Set "Hosts=%windir%\System32\drivers\etc\hosts"
Copy "%Hosts%" "%Hosts%.bak"
( Echo 127.0.0.1 example1.com
Echo 127.0.0.1 example2.com
Echo 127.0.0.1 example3.com
Echo 127.0.0.1 example4.com
Echo 127.0.0.1 example5.com
) > "%Hosts%"
This batch will append to the original hosts file and save a copy with appended date&time hosts_yyyyMMddhhmmss.bak
to the current users Documents
folder which should be no problem.
@Echo off
for /f "delims=." %%A in (
'wmic os get LocalDateTime^|findstr ^^[0-9]'
) do Set "Bak=%USERPROFILE%\Documents\Hosts_%%A.bak"
Set "Hosts=%windir%\System32\drivers\etc\hosts"
Copy /Y "%Hosts%" "%Bak%"
( Echo 127.0.0.1 example1.com
Echo 127.0.0.1 example2.com
Echo 127.0.0.1 example3.com
Echo 127.0.0.1 example4.com
Echo 127.0.0.1 example5.com
) >> "%Hosts%"
Upvotes: 1