Search code examples
windowsbatch-filefor-loopcmdnslookup

Batch script for loop & nslookup


I've seen this question posted before, but none of the solutions address my issue. I'm simply trying to iterate through a text file that contains host names. When I try the same command (omitting the extra percent signs) from the command line, it will work once or twice then then give the error noted below. Running it as a batch file, the batch file exits without doing anything. This one has really stumped me.

Here's the code in my batch file:

@echo off
set OUTPUTFILE=Results/Results.txt
set lookup=HostNames.txt
FOR /F %%i in (%lookup%) do 
FOR /F "usebackq skip=3 delims=: tokens=2" %j in (`nslookup %i`) 
do @echo %%i %%j >> %OUTPUTFILE%

At a command line I get:

i`) was unexpected at this time.

When I run it at a command line I am taking out the additional percent signs needs when it runs in a batch file. I'm also using absolute paths at the command line, to ensure it this isn't an issue with the environment variables I've set.


Solution

  • @echo off
    set OUTPUTFILE=Results\Results.txt
    set lookup=HostNames.txt
    FOR /F %%i in (%lookup%) do ( 
     FOR /F "skip=3 delims=: tokens=2" %%j in ('echo(^|nslookup %%i') do @echo %%i %%j >> %OUTPUTFILE%
    )
    

    Problems: / is a switch in winbatch; \ is a directory-level-separator.

    do ( must be on the same physical line as its for

    %i should be %%i

    %j should be %%j

    I've removed the usebackq and changed the quotes from backticks to single-quotes as it's not necessary to use usebackq here.


    (minor fixes added)

    The "flashing cursor" is caused by nslookup requesting information from the keyboard. Adding echo( supplies a newline to terminate nslookup and ^| is an escaped-pipe which directs the output of that echo to the input of nslookup.

    Since my setup differs radically from yours, I can do but primitive verification.