I summarize the useful suggestions by Liturgist and Alex K. and answer this question to get it removed from list of questions with no answer.
Batch file according to idea provided by Liturgist:
@echo off
if not "%~1" == "" (
if exist "C:\Windows\System32\drivers\etc\hosts_%~1" (
copy /Y "C:\Windows\System32\drivers\etc\hosts_%~1" C:\Windows\System32\drivers\etc\hosts
) else (
echo %~f0 %*
echo.
echo Error: There is no file C:\Windows\System32\drivers\etc\hosts_%~1
echo.
pause
)
) else (
echo %~f0
echo.
echo Please call this batch file with either X or Y as parameter.
echo.
pause
)
The batch file must be called with a parameter which specifies which hosts file should become active with at least hosts_X
and hosts_Y
in directory C:\Windows\System32\drivers\etc
.
The parameter should be either X
or Y
.
An additional file check is made in case of parameter does not specify an existing hosts file resulting in an error message.
There is also a message output if batch file is called without a parameter.
Batch file according to idea provided by Alex K.:
@echo off
if exist C:\Windows\System32\drivers\etc\hosts_X (
ren C:\Windows\System32\drivers\etc\hosts hosts_Y
ren C:\Windows\System32\drivers\etc\hosts_X hosts
echo hosts_X is now the active hosts file.
) else (
ren C:\Windows\System32\drivers\etc\hosts hosts_X
ren C:\Windows\System32\drivers\etc\hosts_Y hosts
echo hosts_Y is now the active hosts file.
)
echo.
pause
This batch file toggles active hosts file depending on which template hosts file currently exists:
- With
hosts_X
existing, hosts
is renamed to hosts_Y
and hosts_X
is renamed to hosts
.
- Otherwise with
hosts_Y
existing, hosts
is renamed to hosts_X
and hosts_Y
is renamed to hosts
.
There should be never hosts
, hosts_X
and hosts_Y
all existing at the same time in the directory as this would result in failing file renames. But all 3 files existing at same time should not be a use case to take into account for this task. (Using move /Y
instead of ren
with second file name having also full path would help in this not to expect use case.)
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
... for an explanation of %~1
, %~f0
and %*
.
copy /?
echo /?
if /?
ren /?
pause /?