Batch script to replace the hosts file with another

Used this batch script as part of a DR failover. I tried different powerShell and batch scripts to replace and add entries directly into the hosts file but most were giving me too many issues.

The batch script below will take a backup of the current hosts file and call it hosts-Original. Then it will move a pre-staged hosts_DR file and rename it to hosts. Instead of doing a lot of DNS updates the application remained the same and only the hosts file was changed.

if exist "C:\Windows\System32\drivers\etc\hosts_DR" (
move "C:\Windows\System32\drivers\etc\hosts" "C:\Windows\System32\drivers\etc\hosts-Original"
move "C:\Windows\System32\drivers\etc\hosts_DR" "C:\Windows\System32\drivers\etc\hosts"
ECHO Renaming current hosts file to hosts-Original
ECHO Activating DR Hosts file
ECHO DR HOSTS FILE IS ACTIVE
Here is the full version of the batch script, it first checks if the command prompt is running as admin, if not then it requests it.
hostsfileswap.bat
----------------------

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop

:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END

:ACCEPTED
if exist "C:\Windows\System32\drivers\etc\hosts_DR" (
move "C:\Windows\System32\drivers\etc\hosts" "C:\Windows\System32\drivers\etc\hosts-Original"
move "C:\Windows\System32\drivers\etc\hosts_DR" "C:\Windows\System32\drivers\etc\hosts"
ECHO Renaming current hosts file to hosts-Original
ECHO Activating DR Hosts file
ECHO DR HOSTS FILE IS ACTIVE

) else (
    ECHO DR Hosts file already in place
)

GOTO END

:END
Pause

This entry was posted in Microsoft, Scripting and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *