Sahil Makhija
Sahil Makhija

Reputation: 5

How to store result of a command in a variable in bat script

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.

Upvotes: 0

Views: 2551

Answers (2)

rene
rene

Reputation: 42494

@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

Upvotes: 1

dbenham
dbenham

Reputation: 130919

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 

Upvotes: 2

Related Questions