0

I have a list of host names separated by new lines in a text file. I want to run netstat on each of those lines and write the output of all these commands to a text file. I know the netstat command will work on each line so thats not an issue.

Here is what I have so far in my .bat:

FOR /F "tokens=*" %%A in (fqdn.txt) do (
    FOR /F "tokens=* USEBACKQ" %%F IN (`netstat %%A`) DO (
        SET var=%%F
    )

    echo %var% >> test.txt
    echo delim >> test.txt
)

All that happens is the netstat help is posted to the command line over and over and the text file fills up with:

ECHO is on.
delim 
ECHO is on.
delim 
ECHO is on.
delim 

Thanks in advance for the help :)

swerly
  • 2,015
  • 1
  • 14
  • 14

1 Answers1

1

You need delayedexpansion because you are setting and using a variable inside of a code block:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%A in (fqdn.txt) do (
for /f "tokens=* USEBACKQ" %%F IN (`netstat %%A`) DO (
    SET var=%%F
  )
   echo !var! >> test.txt
   echo delim >> test.txt
)

To get more detail on delayedexpansion run from cmd set /? and setlocal /?

That being said, you also do not need delayedexpansion:

@echo off
for /f "tokens=*" %%A in (fqdn.txt) do (
for /f "tokens=* USEBACKQ" %%F IN (`netstat %%A`) DO (
    echo %%F >> test.txt
  )
   echo delim >> test.txt
)

As I did not see the actual input file, it is also possible to eliminate the second for loop should you want the entire output from the netstat command.

@echo off
(for /f "tokens=*" %%i in (fqdn.txt) do (
    netstat %%i
    echo delim
 )
)>>test.txt
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • The purpose of the inner `for` loop is to get the *last line* of the `netstat`-output only. – Stephan Oct 31 '19 at 08:26
  • @Stephan True. I did not run the actual command and also did not see OP's original file, so working on assumption. Thanks. Will update. – Gerhard Oct 31 '19 at 08:38
  • Sorry for the delayed response but yeah this helped. Part of my problem was that I was using actually using the command nslookup, but your answer helped guide me. – swerly Nov 27 '19 at 21:02