Skip to main content

How to Add an Entry to the Hosts File in Batch Script

The Windows Hosts File (C:\Windows\System32\drivers\etc\hosts) is a local DNS override. Any entry you add here takes priority over DNS servers, meaning you can redirect a domain name to any IP address you choose, before the request ever leaves the machine. This is invaluable for blocking websites (redirecting them to 127.0.0.1), testing new servers (pointing a production domain to a staging IP), or bypassing DNS propagation delays. Modifying the hosts file requires Administrator privileges because it is protected by the operating system.

This guide will explain how to safely modify the hosts file from the command line.

How the Hosts File Works

DNS Resolution Order:
1. Hosts File → C:\Windows\System32\drivers\etc\hosts
2. DNS Cache → Previously resolved lookups
3. DNS Server → Network-configured DNS (DHCP, manual)

The hosts file is checked FIRST for every DNS lookup. If a matching entry exists, the DNS server is never contacted. This makes it the fastest and most authoritative way to control name resolution on a single machine.

Hosts file format:

# Lines starting with # are comments
# Format: IP_ADDRESS HOSTNAME

127.0.0.1 localhost
::1 localhost

# Custom entries:
127.0.0.1 blocked-site.example.com
192.168.1.50 staging.myapp.com
Administrative Rights Required

The hosts file is a protected system file. You MUST run your script as Administrator to modify it. Without elevation, echo ... >> hosts will fail with "Access is denied."

Method 1: Add a Single Entry with Validation

This method adds a hostname-to-IP mapping with duplicate checking, backup creation, and DNS cache flushing.

Implementation

@echo off
setlocal

set "IP=%~1"
set "Hostname=%~2"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%Hostname%"=="" (
echo Usage: %~nx0 ^<ip_address^> ^<hostname^>
echo.
echo Examples:
echo %~nx0 127.0.0.1 blocked-site.example.com
echo %~nx0 192.168.1.50 staging.myapp.com
echo %~nx0 0.0.0.0 ads.tracker.example.com
endlocal
exit /b 1
)

:: Verify admin privileges
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Modifying the hosts file requires administrator privileges. >&2
echo Right-click and select "Run as administrator." >&2
endlocal
exit /b 1
)

:: Verify the hosts file exists
if not exist "%HostsFile%" (
echo [ERROR] Hosts file not found: %HostsFile% >&2
endlocal
exit /b 1
)

:: Check if entry already exists
findstr /i /c:"%Hostname%" "%HostsFile%" >nul 2>&1
if not errorlevel 1 (
echo [SKIP] An entry for "%Hostname%" already exists in the hosts file:
findstr /i /c:"%Hostname%" "%HostsFile%"
echo.
echo To update it, remove the old entry first, then add the new one.
endlocal
exit /b 0
)

:: Create a backup before modifying
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1
if errorlevel 1 (
echo [WARNING] Could not create backup of hosts file. >&2
)

:: Validate IP format (basic check)
set "validIP=0"
for /f "tokens=1-4 delims=." %%a in ("%IP%") do (
if not "%%d"=="" set "validIP=1"
)
if "%validIP%"=="0" (
echo [WARNING] "%IP%" doesn't look like a standard IPv4 address. >&2
echo Proceeding anyway ^(may be an IPv6 address or intentional^). >&2
)

:: Add the entry with a comment
echo. >> "%HostsFile%"
echo # Added by %USERNAME% on %date% %time% >> "%HostsFile%"
echo %IP% %Hostname% >> "%HostsFile%"

if errorlevel 1 (
echo [ERROR] Failed to write to hosts file. >&2
endlocal
exit /b 1
)

echo [OK] Added: %IP% %Hostname%

:: Flush DNS cache to apply immediately
ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed. The new mapping is active immediately.

endlocal
exit /b 0

Why the script adds a comment line:

The comment # Added by jsmith on Fri 05/10/2024 14:32:05 documents who added the entry and when. Without this, hosts file entries accumulate over months and no one remembers why they were added or whether they're still needed. The comment provides accountability and makes cleanup audits possible.

Why 0.0.0.0 vs. 127.0.0.1 for blocking:

Target IPEffectSpeed
127.0.0.1Redirects to localhost: connection attempt to selfSlightly slower (TCP connection attempt then rejection)
0.0.0.0Drops the request immediately: no connection attemptFaster (fails instantly)

Both effectively block the domain. 0.0.0.0 is slightly more efficient because the system doesn't attempt a TCP connection.

Method 2: Block Multiple Domains

For content filtering, ad blocking, or security policy enforcement: block a list of domains by redirecting them to 0.0.0.0.

@echo off
setlocal EnableDelayedExpansion

set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"
set "BlockIP=0.0.0.0"

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

:: Create backup
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

echo [ACTION] Applying domain block list...
echo.

set "Added=0"
set "Skipped=0"

:: Block list: add or remove domains as needed
for %%s in (
"ads.example.com"
"tracker.example.com"
"analytics.unwanted.com"
"malware-domain.example.com"
"telemetry.suspicious.net"
) do (
findstr /i /c:"%%~s" "%HostsFile%" >nul 2>&1
if errorlevel 1 (
echo %BlockIP% %%~s >> "%HostsFile%"
echo [BLOCKED] %%~s
set /a "Added+=1"
) else (
echo [SKIP] %%~s (already in hosts file^)
set /a "Skipped+=1"
)
)

echo.
echo [DONE] Added: !Added! Skipped: !Skipped!

:: Flush DNS
ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed.

endlocal
exit /b 0

Loading block list from a file:

For large block lists, maintain the domains in a separate text file (one per line) and read from it:

:: block_list.txt:
:: ads.example.com
:: tracker.example.com
:: analytics.unwanted.com

for /f "usebackq tokens=*" %%s in ("%~dp0block_list.txt") do (
findstr /i /c:"%%s" "%HostsFile%" >nul 2>&1
if errorlevel 1 (
echo %BlockIP% %%s >> "%HostsFile%"
)
)
Hosts File Size and Performance

The hosts file is read sequentially for every DNS lookup. Very large hosts files (thousands of entries) can slightly slow DNS resolution. For enterprise-scale ad blocking or domain filtering, use DNS-level solutions (Pi-hole, DNS sinkhole, or Group Policy DNS filtering) rather than the hosts file.

Method 3: Development/Testing Redirect

Point a production domain to a local or staging server for testing: see your changes on a production URL without affecting anyone else.

@echo off
setlocal

set "StagingIP=%~1"
set "ProdDomain=%~2"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%ProdDomain%"=="" (
echo Usage: %~nx0 ^<staging_ip^> ^<production_domain^>
echo.
echo Redirects a production domain to a staging/development server.
echo.
echo Examples:
echo %~nx0 192.168.1.50 myapp.company.com
echo %~nx0 10.0.0.100 api.myservice.com
echo.
echo To remove the redirect, use the removal script.
endlocal
exit /b 1
)

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

:: Warn if domain already has an entry
findstr /i /c:"%ProdDomain%" "%HostsFile%" >nul 2>&1
if not errorlevel 1 (
echo [WARNING] An entry for %ProdDomain% already exists:
findstr /i /c:"%ProdDomain%" "%HostsFile%"
echo.
set /p "Overwrite=Add another entry anyway? (YES/no): "
if /i not "!Overwrite!"=="YES" (
echo [INFO] Cancelled.
endlocal
exit /b 0
)
)

:: Backup
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

:: Add the redirect with a prominent comment
echo. >> "%HostsFile%"
echo # DEV REDIRECT: %ProdDomain% -^> %StagingIP% (by %USERNAME% on %date%) >> "%HostsFile%"
echo %StagingIP% %ProdDomain% >> "%HostsFile%"

echo [OK] %ProdDomain% now resolves to %StagingIP% on this machine.
echo.
echo [IMPORTANT] This redirect is LOCAL ONLY. Other machines still resolve
echo %ProdDomain% via DNS to the production server.
echo.
echo [REMEMBER] Remove this entry when testing is complete!

ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed. Redirect is active.

endlocal
exit /b 0
Verify the Redirect is Working

After adding a development redirect, verify it's resolving correctly:

nslookup myapp.company.com
:: Should show "Non-authoritative answer" with the STAGING IP
:: Note: nslookup bypasses the hosts file! Use ping instead:
ping -n 1 myapp.company.com
:: The "Pinging myapp.company.com [192.168.1.50]" line confirms the redirect

nslookup queries DNS servers directly and ignores the hosts file. Use ping to verify hosts file entries.

Method 4: Remove an Entry from the Hosts File

When a block or redirect is no longer needed, remove it cleanly.

@echo off
setlocal

set "Hostname=%~1"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%Hostname%"=="" (
echo Usage: %~nx0 ^<hostname_to_remove^>
echo.
echo Removes all entries for the specified hostname from the hosts file.
echo.
echo Example: %~nx0 staging.myapp.com
endlocal
exit /b 1
)

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

:: Check if the entry exists
findstr /i /c:"%Hostname%" "%HostsFile%" >nul 2>&1
if errorlevel 1 (
echo [INFO] No entry for "%Hostname%" found in the hosts file.
endlocal
exit /b 0
)

echo [INFO] Current entries for "%Hostname%":
findstr /i /c:"%Hostname%" "%HostsFile%"
echo.

set /p "Confirm=Remove all entries for "%Hostname%"? (YES/no): "
if /i not "%Confirm%"=="YES" (
echo [INFO] Cancelled. No changes made.
endlocal
exit /b 0
)

:: Backup
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

:: Remove the entry by writing all OTHER lines to a temp file
set "TempFile=%TEMP%\hosts_temp_%RANDOM%.txt"

findstr /v /i /c:"%Hostname%" "%HostsFile%" > "%TempFile%"

:: Replace the original with the filtered version
copy /y "%TempFile%" "%HostsFile%" >nul 2>&1

if errorlevel 1 (
echo [ERROR] Failed to update hosts file. >&2
echo Restoring from backup... >&2
copy /y "%HostsFile%.bak" "%HostsFile%" >nul 2>&1
del "%TempFile%" 2>nul
endlocal
exit /b 1
)

del "%TempFile%" 2>nul

echo [OK] All entries for "%Hostname%" removed.

ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed.

endlocal
exit /b 0
Comment Lines May Be Left Behind

The removal script removes lines containing the hostname, but comment lines (e.g., # DEV REDIRECT: staging.myapp.com) that contain the hostname will also be removed by findstr /v. Comment lines that don't contain the hostname will remain. For complete cleanup, review the hosts file manually after automated removal.

Method 5: View Current Custom Entries

Display all non-default entries in the hosts file for auditing.

@echo off
setlocal

set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

echo [INFO] Custom entries in the hosts file:
echo --------------------------------------------------

:: Show non-comment, non-empty, non-localhost lines
findstr /v /r "^#" "%HostsFile%" | findstr /v /r "^$" | findstr /v /i "localhost" 2>nul

if errorlevel 1 (
echo (No custom entries found)
)

echo --------------------------------------------------
echo.
echo [INFO] Full hosts file location: %HostsFile%
echo [INFO] Total lines:
find /c /v "" "%HostsFile%"

endlocal
exit /b 0

How to Avoid Common Errors

Wrong Way: Forgetting to Flush DNS

After modifying the hosts file, Windows may still use cached DNS resolutions. The change won't take effect until the cache expires (which can take minutes).

Correct Way: Always run ipconfig /flushdns after editing the hosts file. All methods in this guide include this step.

Wrong Way: Not Checking for Duplicates

:: CREATES DUPLICATES: appends every time the script runs
echo 127.0.0.1 blocked-site.com >> hosts

Running the script multiple times creates multiple identical entries. While Windows handles duplicates without errors, they make the hosts file messy and confusing during troubleshooting.

Correct Way: Use findstr to check for existing entries before appending (Method 1).

Problem: nslookup Shows the Wrong IP After Hosts Edit

nslookup queries DNS servers directly and bypasses the hosts file entirely. It will always show the DNS server's answer, not the hosts file override.

Solution: Use ping to verify hosts file entries:

ping -n 1 staging.myapp.com
:: Shows: Pinging staging.myapp.com [192.168.1.50]
:: The IP in brackets confirms the hosts file is working

Problem: Antivirus Blocks Hosts File Modification

Some antivirus products protect the hosts file against modification, treating any change as a potential malware action (malware often modifies the hosts file to redirect banking sites).

Solution: Temporarily disable the antivirus's hosts file protection, make the change, then re-enable it. Or add an exception in the antivirus for your management script.

Problem: Encoding Issues

The hosts file must be saved as ANSI or UTF-8 without BOM. If a script writes to it using an incompatible encoding, Windows may not parse the entries correctly.

Solution: Batch's echo ... >> file writes in the system's default encoding (typically ANSI), which is correct for the hosts file. Do not use PowerShell's Out-File (which defaults to UTF-16) to write to the hosts file.

Best Practices and Rules

1. Always Check for Duplicates Before Adding

Use findstr to verify an entry doesn't already exist. Duplicate entries create confusion during troubleshooting.

2. Always Flush DNS After Changes

ipconfig /flushdns clears the DNS resolver cache, making hosts file changes take effect immediately.

3. Always Create a Backup

Before any modification, copy the hosts file to hosts.bak. If a bad entry breaks connectivity, restoring the backup is faster than debugging:

copy "%HostsFile%" "%HostsFile%.bak" >nul

4. Add Comments for Accountability

Document who added each entry and why. Months later, no one will remember why staging.myapp.com points to 192.168.1.50 unless there's a comment explaining it.

5. Remove Development Entries When Done

Development redirects left in the hosts file cause subtle, hard-to-diagnose issues when the developer forgets about them. Set a reminder to remove temporary entries after testing is complete.

6. Use DNS for Enterprise-Scale Blocking

The hosts file works well for a handful of entries. For blocking hundreds or thousands of domains, use DNS-level solutions (DNS sinkhole, Pi-hole, Group Policy DNS filtering) that centralize management and don't impact per-machine file I/O.

Conclusions

Adding entries to the hosts file provides fast, authoritative, local-only DNS override, whether for blocking unwanted domains, redirecting production URLs to staging servers, or bypassing DNS propagation delays.

By automating this with duplicate checking, backup creation, comment documentation, DNS cache flushing, and a corresponding removal script, you turn a manual text-editor operation into a reliable, auditable process.

Remember that hosts file entries are local to the machine and invisible to the rest of the network: this is powerful for testing, but not a substitute for proper DNS management.