views:

817

answers:

2

I'm trying to write a batch script that errors if port 1099 is already in use.

Unfortunately I have to write it in a DOS batch script (I cannot install anything).

I know that I can print the PID of the process hogging port 1099 manually:

netstat -aon | findstr ":1099"

But I want to be able to run that command in a batch script and exit the script with an error message if that command has any output.

I suppose at a push I could redirect the output to a temporary file and test the size of it but that seems really hacky...

+7  A: 
 netstat -an | FINDSTR ":1099" | FINDSTR LISTENING && ECHO Port is in use && EXIT 1

You can use && in a batch script to run a command only if the previous command was successful (based on its exit code/ERRORLEVEL). This allows you to display a message and exit only if the string you are looking for is found in the output of netstat.

Also, you want to explicitly look for LISTENING ports.

FINDSTR supports regular expressions so you can also do the following to shorten the command line:

netstat -an | findstr /RC:":1099 .*LISTENING" && ECHO Port is in use && EXIT 1
Dave Webb
Wow, thanks. I just tested it and it works perfectly.And you also noted the "o" switch was redundant, bonus ;)
floater81
A: 

Hmmmm can this be used in an if statement? like if %var1%==1 && if %var2%==2 COMMAND or can you on any other how do this?

jacks