Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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=10.1.1.1 test.testing.com
FOR /F "usebackq delims==`" %%A IN (`findstr /c:"10.1.1.1 test.testing.com"  %SystemRoot%\system32\drivers\etc\hosts`) do SET search=%%A
if NOT "%search%"=="%compare%" echo Do Something >> output.txt

If I change:

"%search%"=="%compare%"

To:

"sometext"=="sometext"

It works fine. If I echo the output of %search% and %compare% I get:

10.1.1.1 test.testing.com
10.1.1.1 test.testing.com
share|improve this question

1 Answer 1

Yeah,

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

@echo off
SET compare=10.1.1.1 blah.blah.com
FOR /F "usebackq delims==`" %%A IN (`findstr /c:"blah.blah.com" %SystemRoot%\system32\drivers\etc\hosts`) do SET compared=%%A
if NOT "%compare%"=="%compared%" echo 10.1.1.1 blah.blah.com>> %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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.