Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch: How to add Host-Entries?

I want to use this batch script to add new entries into my host file automatically by using windows batch.

Unfortunately, the script just adds one single line to the hosts file, also when i run the script as a administrator, so what's wrong?

@echo off  set hostspath=%windir%\System32\drivers\etc\hosts  echo 62.116.159.4 ns1.intranet.de >> %hostspath% echo 217.160.113.37 ns2.intranet.de >> %hostpath% echo 89.146.248.4 ns3.intranet.de >> %hostpath% echo 74.208.254.4 ns4.intranet.de >> %hostpath%  exit 
like image 493
mate64 Avatar asked Sep 08 '10 10:09

mate64


People also ask

How do I add a host to my table?

Right-click TCP/IP Configuration and select Host Table to open the Host Table window. The Host Table window shows the host names of each entry (both IPv4 and IPv6 addresses). Each host table entry can contain up to 65 host names. Use the Host Table window to add, edit, or remove host table entries.

How do I find my host entries in Windows?

Press Windows Key + R. Type %WinDir%\System32\Drivers\Etc into the Run window and click OK. Open the hosts file with a text editor such as Notepad. Hosts will not have a file extension.


2 Answers

I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.

@echo off  SET NEWLINE=^& echo.  FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts  FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts  FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts  FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts 
like image 107
todd Avatar answered Oct 27 '22 11:10

todd


Plain typo. hostspath vs hostpath ;)

@echo off   set `hostspath`=%windir%\System32\drivers\etc\hosts   echo 62.116.159.4 ns1.intranet.de >> `%hostspath%`    echo 217.160.113.37 ns2.intranet.de >> `%hostpath%`   echo 89.146.248.4 ns3.intranet.de >> `%hostpath%`    echo 74.208.254.4 ns4.intranet.de >> `%hostpath%`     exit  
like image 25
Kirill Leontev Avatar answered Oct 27 '22 10:10

Kirill Leontev