Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The What

I'm writing a short script to push out a new line to everyone in my domains hosts file in a GPO - don't ask why we're not doing this via DNS, the reasons are both fun and extensive :)

For the most part, this is simple, however I'm hitting upon a somewhat obstinate problem with comparing strings in variables, namely, it doesn't seem to do it. The strings don't seem to match, despite the fact if I echo out the strings they are identical. With the strings not matching, it just keeps adding a line to the end of the hosts file ad infinitum.

For reference, this is the process I want the script to follow:

The How

Set compare value -> Search hosts file for existing entries and save output to variable -> Compare variables if match, do nothing, else

The Code

@echo off
SET compare=
FOR /F "usebackq delims==`" %%A IN (`findstr /c:""  %SystemRoot%\system32\drivers\etc\hosts`) do SET search=%%A
if NOT "%search%"=="%compare%" echo Do Something >> output.txt

If I change:




It works fine. If I echo the output of %search% and %compare% I get:
share|improve this question


So I eventually figured this out, whitespace was my issue. A very minor change to the script resolved the problem.

@echo off
SET compare=
FOR /F "usebackq delims==`" %%A IN (`findstr /c:"" %SystemRoot%\system32\drivers\etc\hosts`) do SET compared=%%A
if NOT "%compare%"=="%compared%" echo>> %SystemRoot%\system32\drivers\etc\hosts
set compare=
set compared=
share|improve this answer
Please remember that you can mark your own answer as the solution to your question :) – Oliver Salzburg Jul 11 '12 at 12:21
Can you describe this issue a little more. I am facing the same issue in my batch file and I cant fix it from this answer.. – tumchaaditya Mar 10 '13 at 5:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .