Search code examples
windowsbatch-filecmdnetstat

Windows cmd batch file write multiple netstat outputs to text file


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 :)


Solution

  • 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