20

Is there a way in powershell to check if a given port is in use or not?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Jeevan
  • 8,532
  • 14
  • 49
  • 67

4 Answers4

38

Use Get-NetTCPConnection

Get-NetTCPConnection | where Localport -eq 5000 | select Localport,OwningProcess

Localport OwningProcess
--------- -------------
    5000          1684
NoName
  • 7,940
  • 13
  • 56
  • 108
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
3

If you are using PowerShell Core v6 and above use Test-Connection

>Test-Connection localhost -TcpPort 80
True
Kyle Nunery
  • 2,048
  • 19
  • 23
1

Following the other answers, once you run Get-NetTCPConnection | where Localport -eq 5000 | select Localport,OwningProcess you can check which process/application is using the port by running Get-Process

Get-Process -Id <OwningProcess>
crisleo94
  • 97
  • 1
  • 9
  • How would this call find details about a port? – T. Nielsen Aug 10 '22 at 08:18
  • 2
    Once you get the OwningProcess with this `Get-NetTCPConnection | where Localport -eq 5000 | select Localport,OwningProcess` you then run `Get-Process -Id ` and you know wich application or process is using the port so you can kill that process from the task manager – crisleo94 Aug 10 '22 at 14:00
  • Yes i mean exactly You need both to get the answer in this better detail, i would recommend updating Your solution to contain both perhaps even using an array variable to store the result and look the other thing up to flex Your script muscles and surely be better and more complete than the other suggestions in themselves to totally justify why yours is a viable and relevant addition to the other suggestion(s) – T. Nielsen Aug 22 '22 at 12:27
0

You could just roll it into one:

Get-NetTCPConnection | where Localport -eq 5000| Select-Object Localport,@{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}}

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 03 '22 at 09:52