Page 1 of 1
Get PID from port
Posted: 11 Mar 2019 11:54
by Docfxit
I have a syntax error when trying to get the PID from a port number:
Code: Select all
for /f "tokens=5" %a in ('netstat -aon ^| findstr 80') do tasklist /FI "PID eq %a"
Thanks,
Docfxit
Re: Get PID from port
Posted: 11 Mar 2019 12:20
by aGerman
I suspect it's because of the FOR variables. In a batch script you have to double the percent signs.
Steffen
Re: Get PID from port
Posted: 11 Mar 2019 14:00
by Docfxit
That fixed the error really great.
Do you have any idea why the port isn't being substituted in this code?
Code: Select all
set "Port#=80"
for /f "tokens=5" %%a in ('netstat -aon ^| findstr %Port#%') do tasklist /FI "PID eq %%a"
Thank you,
Docfxit
Re: Get PID from port
Posted: 11 Mar 2019 15:07
by aGerman
I don't know what you are expecting. First of all you should enclose the search string into quotes for the findstr command. And instead of "80" you should rather look for ":80\>" where \> marks the right word boundary as explained in the help of findstr. For your command that would mean
findstr ":%Port#%\>"
Steffen
Re: Get PID from port
Posted: 11 Mar 2019 15:34
by Squashman
You used it correctly in previous questions you have asked on the forums.
Eighth line of the help file for the FOR command.
To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.
Re: Get PID from port
Posted: 11 Mar 2019 18:52
by Docfxit
aGerman wrote: ↑11 Mar 2019 15:07
I don't know what you are expecting. First of all you should enclose the search string into quotes for the findstr command. And instead of "80" you should rather look for ":80\>" where \> marks the right word boundary as explained in the help of findstr. For your command that would mean
findstr ":%Port#%\>"
Steffen
That worked perfectly . Thank you very much.
Docfxit