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...
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.
&& 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 ).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With