Get PID from port

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Docfxit
Posts: 21
Joined: 12 Nov 2015 12:42

Get PID from port

#1 Post by Docfxit » 11 Mar 2019 11:54

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"

Code: Select all

a" was unexpected at this time.
Thanks,
Docfxit

aGerman
Expert
Posts: 3522
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Get PID from port

#2 Post by aGerman » 11 Mar 2019 12:20

I suspect it's because of the FOR variables. In a batch script you have to double the percent signs.

Steffen

Docfxit
Posts: 21
Joined: 12 Nov 2015 12:42

Re: Get PID from port

#3 Post by Docfxit » 11 Mar 2019 14:00

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

aGerman
Expert
Posts: 3522
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Get PID from port

#4 Post by aGerman » 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

Squashman
Expert
Posts: 4074
Joined: 23 Dec 2011 13:59

Re: Get PID from port

#5 Post by Squashman » 11 Mar 2019 15:34

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.

Docfxit
Posts: 21
Joined: 12 Nov 2015 12:42

Re: Get PID from port

#6 Post by Docfxit » 11 Mar 2019 18:52

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

Post Reply