title: How to edit hosts file using a batch file (check for line, add if not existing and delete if existing)?
body: <p>I have a batch script to add several lines to my hosts file to block certain websites on my computer.</p>
  
  <p>I would like to use the batch script in such a way that when I run my <code>example.bat</code>, it first checks if the lines to add exist, and if they don't then add them. But the batch file should delete the lines in case of existing already in <code>hosts</code> file. In other words the batch file should toggle the presence of the lines in the <code>hosts</code> file.</p>
  
  <p>How could this be done?</p>
  
  <p>Here is what I have so far. All it does is adding the lines.</p>
  
  <pre><code>@echo off
  
  :: BatchGotAdmin
  ::-------------------------------------
  REM  --&gt; Check for permissions
  &gt;nul 2&gt;&amp;1 "%SystemRoot%\system32\cacls.exe" "%SystemRoot%\system32\config\system"
  
  REM --&gt; If error flag set, we do not have administrator privileges.
  if not errorlevel 1 goto gotAdmin
  
  echo Set UAC = CreateObject^("Shell.Application"^) &gt;"%temp%\getadmin.vbs"
  set params=%*
  if defined params set params=%params:"=""%
  echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 &gt;&gt; "%temp%\getadmin.vbs"
  
  "%temp%\getadmin.vbs"
  del "%temp%\getadmin.vbs"
  exit /B
  
  :gotAdmin
  pushd "%CD%"
  CD /D "%~dp0"
  ::--------------------------------------
  
  @echo off
  
  set hostspath=%SystemRoot%\System32\drivers\etc\hosts
  
  echo 127.0.0.1 www.example1.com &gt;&gt; %hostspath%
  echo 127.0.0.1 www.example2.com &gt;&gt; %hostspath%
  echo 127.0.0.1 www.example3.com &gt;&gt; %hostspath%
  
  exit
  </code></pre>