Skip to content

Instantly share code, notes, and snippets.

@amitbhoraniya
Created October 9, 2017 17:47
Show Gist options
  • Save amitbhoraniya/9b986f04b698277cea045e6da0e1e2cf to your computer and use it in GitHub Desktop.
Save amitbhoraniya/9b986f04b698277cea045e6da0e1e2cf to your computer and use it in GitHub Desktop.
@echo off
setlocal enableextensions
:: search for available ports
call :findFirstAvailablePort 8080 tomcatPort
call :findFirstAvailablePort 1521 oraclePort
:: echo the retrieved data
echo Tomcat_port=%tomcatPort%
echo Oracle_port=%oraclePort%
endlocal
exit /B
:findFirstAvailablePort startingPort returnVariable
setlocal enableextensions
:: Generate a list of the open ports and save in temporary file
set "tempFile=%temp%\%~nx0.tmp"
((@for /f "tokens=2" %%a in ('netstat -an -p tcp'
) do @for /f "tokens=1,2 delims=]" %%b in ("%%a"
) do @if "%%c"=="" (@echo(x%%b) else (@echo(%%c)
)|@for /f "tokens=2 delims=: " %%d in ('more') do @echo($%%d$) > "%tempFile%"
:: Test temporary file for next available port
(break|@for /l %%p in (%~1 1 65535) do @(
find "$%%p$" "%tempFile%" >nul || exit %%p
if %%p==65535 exit 0
))
set "port=%errorlevel%"
:: clean and exit returning port
endlocal & del /q "%tempFile%" 2>nul & set "%~2=%port%" & exit /b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment