Home > front end >  How to determine the port on which a Windows service is listening?
How to determine the port on which a Windows service is listening?

Time:11-03

I have running a Windows service called my-service. The only input that I know is the service name.

I can get the process identifier by using the service name:

$id = Get-WmiObject -Class Win32_Service -Filter "name='my-service'" | Select-Object -ExpandProperty ProcessId

To get a list of Listening ports, I can use netstat, but all my custom services have PID 4 which is not equal to the service process identifier of Get-WmiObject cmdlet.

netstat.exe -ano

The goal is to get the port on which the service is listening by using PowerShell or CMD based on the service name or the process identifier and NOT by the image name.

CodePudding user response:

Use Get-NetTCPConnection to identify sockets on which the given process is currently listening:

Get-NetTCPConnection -OwningProcess $id -State Listen

CodePudding user response:

Might you could combine Get-NetTcpConnection -OwningProcess XXXX with How to get process id by its service name with a script to variable?

CodePudding user response:

As you have included the tag, here's an idea you could try, in the cmd.exe, i.e. Windows Command Prompt:

For /F "Tokens=2 Delims=," %G In ('%SystemRoot%\System32\tasklist.exe /SVC /Fi "Services Eq my-service" /Fo CSV /NH 2^>NUL') Do @For /F "Tokens=3 Delims=: " %H In ('%SystemRoot%\System32\netstat.exe -ano ^| %SystemRoot%\System32\findstr.exe "[^0123456789]%~G$" ^| %SystemRoot%\System32\find.exe /V "["') Do @Echo %H

Just change my-service to your 'real' service name.

  • Related