Toggle between two hosts files with a simple script

A longtime reader wrote in asking if it was possible to easily toggle between two hosts files. There are several possible uses for this. When I’m at home, I need to address my web site by its internal, private IP address. On the road, that private address obviously doesn’t work. He wants something like this for other reasons; I believe he’s blocking ad servers with his hosts file and needs to unblock one or more servers temporarily for select sites to work properly.

This solution would make my Computer Science 203 professor rescind the B I received in his class if he saw it, but it works, and I don’t think he reads this blog anyway.


To get started, leave the existing file at c:\windows\system32\drivers\etc\hosts alone. Save a modified hosts file as c:\windows\system32\drivers\etc\hosts.1 and then copy this simple batch file, listed below, into Notepad, and save it as hoststoggle.bat. Store it somewhere convenient, and will toggle between the two hosts files when run. On Windows Vista and Windows 7, you’ll have to right-click and select Run as Administrator for it to work properly. (The 500,000 of you already running Windows 8 are on your own–I’m still in the thinking-about-it stage.) On Windows XP it just works if you’re logged in with admin rights.

rem hoststoggle.bat
rem toggle hosts files

if exist %windir%\system32\drivers\etc\hosts.1 goto One
if exist %windir%\system32\drivers\etc\hosts.2 goto two

:One
ren %windir%\system32\drivers\etc\hosts hosts.2
ren %windir%\system32\drivers\etc\hosts.1 hosts
goto done

:two
ren %windir%\system32\drivers\etc\hosts hosts.1
ren %windir%\system32\drivers\etc\hosts.2 hosts

:done
echo Exiting....

This simple batch file should also work on Windows 2000 and earlier versions of Windows NT. And by changing each instance of %windir%\system32\drivers\etc\ to c:\windows\, it probably would work on Windows 95, 98, and ME. But I don’t have a way to test it on any of those older systems anymore.

If you find stuff like this useful, I’ve collected most of my scripting resources in a single post about scripting Windows sysadmin tasks.

%d bloggers like this:
WordPress Appliance - Powered by TurnKey Linux