Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch script to print error message if port in use

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...

like image 999
matt burns Avatar asked May 12 '09 09:05

matt burns


People also ask

What does %1 do in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

What is && in batch?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).

How do I check batch file errors?

To test for a specific ERRORLEVEL, use an IF command with the %ERRORLEVEL% variable. n.b. Some errors may return a negative number. If the batch file is being executed as a scheduled task, then exiting with an error code will be logged as a failed task. You can monitor the event log to discover those failures.


1 Answers

 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
like image 157
Dave Webb Avatar answered Sep 24 '22 04:09

Dave Webb