Reputation: 1279
I am writing a batch file to automate certain redundant tasks. In the process, I need to find a port that is not listening so I can use it to install some services.
The current test code I have is:
@echo OFF
:getPort
Set /P oPort=Enter an open port (not listening) (eg: 9335)
echo %oPort%
for /f "delims=" %%a in ('netstat -an |find /i "%oPort%"') do (
call set concat=%%concat%%%%a
)
echo %concat%
IF [%concat%] != []
echo %oPort% is already in use.
GOTO getPort
It throws error | was unexpected at this time.
What I am trying to do in the code is:
netstat -an | find /i 9225
and store the output value in a variableAny guidance, please.
Upvotes: 0
Views: 1924
Reputation: 70923
netstat -an | findstr /r /c:"^ [TU][CD]P *[^ ]*:%oPort% " >nul && goto :getPort
There is no need for the for
command. Just test if the value can be found. If it can be found ask for another port.
Upvotes: 0
Reputation: 6630
Instead of using a for-loop to extract the output, I would suggest redirecting it into a file and going of that.
@echo OFF
:getPort
Set /P oPort=Enter an open port (not listening) (eg: 9335)
echo %oPort%
netstat -an |find /i "%oPort%"' > temp.tmp
set /p concat=<temp.tmp
del temp.tmp
echo %concat%
IF "%concat%" NEQ "" (
echo %oPort% is already in use.
GOTO getPort
)
echo %oPort% is not in use.
REM Not sure if you want to exit or continue
goto getport
Which should work.
Upvotes: 1