Xelian
Xelian

Reputation: 17198

Check hosts file for entity using batch script in Windows 7?

I have hosts file with entity in it address:hosts and want to check if given entity presents in the hosts file. So I wrote: In hosts file:

# Copyright (c) 1993-2009 Microsoft Corp.
129.0.2.2 tralala.com

And in my batch script i wrote:

@if "%DEBUG%" == "" @echo off

@rem ############################################
@rem # Remove host from windows hosts file      #
@rem ############################################

if "%OS%"=="Windows_NT" setlocal

:start
set "hostpath=%systemroot%\system32\drivers\etc\hosts"
goto addFindIPAddress

:addFindIPAddress
@rem set the string you wish to find
set find="129.0.2.2 tralala.com"
goto checkHosts

:checkHosts
for /f "tokens=*" %%a in (%hostpath%) do call :processline %%a
goto :mainEnd

:processline
set line=%*
if NOT line == find (
echo %line%
)
goto :eof

:mainEnd
if "%OS%"=="Windows_NT" endlocal
PAUSE

So I want to print all lines that are different from find line but nothing happens so I am wondering were is my wrong?

Upvotes: 1

Views: 246

Answers (1)

David Ruhmann
David Ruhmann

Reputation: 11367

The batch comparison operator == is space sensitive and the variables must be expanded for comparison. The spaces around the == operator must be removed and the variables must be expanded or just the variable names will be compared.

if not "%line%"=="%find%" (

That is the primary issue with your script. However, I would recommend using the find command to perform this task.

find /v "129.0.2.2 tralala.com" "%systemroot%\system32\drivers\etc\hosts"

Upvotes: 2

Related Questions