How can I find a free port with a batch file?
I tried to run a loop and using the netstat -o -n -a it will increment a variable until the port is not found in the netstat list
But I'm also not sure if this is the best way to find a free port.
set freePort= set startPort=80 :SEARCHPORT netstat -o -n -a | findstr ":%startPort%" if %ERRORLEVEL% equ 0 ( echo "port unavailable %ERRORLEVEL%" set /a startPort +=1 GOTO :SEARCHPORT ) ELSE ( echo "port available %ERRORLEVEL%" set freePort=%startPort% GOTO :FOUNDPORT ) :FOUNDPORT echo free %freePort% 32 Answers
You'll need to change your
netstat -o -n -a | findstr ":%startPort%" in
netstat -o -n -a | find "LISTENING" | find ":%startPort% " The find "LISTENING" limits your search to only incoming listening ports and you need the space after the lat % because else you'll match :8085 too.
You also had some other errors in your .bat.
- In the if statement you needed to wrap the
%ERRORLEVEL%around". - You need the
(on the same line as the if statement. - I changed the echo from %ERRORLEVEL% to echo the %startPort%.
Here is a correct working one:
@echo off set freePort= set startPort=80 :SEARCHPORT netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL if "%ERRORLEVEL%" equ "0" ( echo "port unavailable %startPort%" set /a startPort +=1 GOTO :SEARCHPORT ) ELSE ( echo "port available %startPort%" set freePort=%startPort% GOTO :FOUNDPORT ) :FOUNDPORT echo free %freePort% 2Usually net stat command of windows would help you to find port statistics
You could try like this using conditional statements
@echo off netstat -o -n -a | findstr ZXCZXCZCZX if %ERRORLEVEL% equ 0 (@echo "port is available") ELSE (@echo "port is unavailable") 0