0
FOR /F "tokens=1 delims=" %%A in ('netstat -ano | findstr 7001') do SET   myVar=%%A 
echo %myVar% 

Command says that it does not recognize | before findstr, can anyone help me out here.

2 Answers 2

2

Special characters like | must either be escaped or quoted when within IN() clause. Note that the TOKENS=1 option is not needed - it is the default.

You can use either

for /f "delims=" %%A in ('netstat -ano ^| findstr 7001') do set myVar=%%A 

or

for /f "delims=" %%A in ('"netstat -ano | findstr 7001"') do set myVar=%%A 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @dbenham i modified my code accordingly and got my ans this is the code for /f " tokens=1,2* delims=" %%a in ('netstat -ano ^| findstr 7001') do set myVar=%%a echo %myvar:~-4% pause
1
@echo off
set portnumber=?

FOR /F "tokens=1,2,3,4,* delims= " %%a in ('netstat -ano') do call :handleline %%a %%b %%c %%d %%e

goto :eof

:handleLine
call :portcheck %1 %2 %2 %4 %5

rem you can have your check here
rem if %portnumber%==7001 do whatever
echo pid %4 uses port %portnumber%

goto :eof

:portcheck
set prot=%1
set ipandport=%2
set pid=%4

set pn1=%ipandport:~-1%
set pn2=%ipandport:~-2%
set pn3=%ipandport:~-3%
set pn4=%ipandport:~-4%
set pn5=%ipandport:~-5%

if !%pn2:~0,1%!==!:! set portnumber=%pn1% & goto :bailout
if !%pn3:~0,1%!==!:! set portnumber=%pn2% & goto :bailout
if !%pn4:~0,1%!==!:! set portnumber=%pn3% & goto :bailout
if !%pn5:~0,1%!==!:! set portnumber=%pn4% & goto :bailout
set portnumber=%pn5%
:bailout

goto :eof

1 Comment

hi actually i wanted to get the pid by comparing the port number in the result which i get after doing netstat -ano | find 7001 This code returned C:\Users\sahil.makhija>netstat -ano | findstr 7001 TCP 0.0.0.0:7001 0.0.0.0:0 LISTENING 5148 TCP [::]:7001 [::]:0 LISTENING 5148 so i had to make some changes in your code which helped me out. This is the new code FOR /F "tokens=1,2,5* delims= " %%a in ('netstat -ano') do if %%b==0.0.0.0:7001 set myvar=%%c echo %myvar% pause this stored my PID into myvar.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.