FOR /F "tokens=1 delims=" %%A in ('netstat -ano | findstr 7001') do SET myVar=%%A
echo %myVar%
命令说它在|
之前无法识别findstr
,任何人都可以帮助我。
答案 0 :(得分:2)
在IN()子句中,必须对|
之类的特殊字符进行转义或引用。请注意,不需要TOKENS = 1选项 - 这是默认选项。
您可以使用
for /f "delims=" %%A in ('netstat -ano ^| findstr 7001') do set myVar=%%A
或
for /f "delims=" %%A in ('"netstat -ano | findstr 7001"') do set myVar=%%A
答案 1 :(得分: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