Created
January 21, 2022 18:31
-
-
Save pmarreck/b37a0cc6cffd811f9e308b7895fdfec4 to your computer and use it in GitHub Desktop.
On Windows, use PowerShell to get a list of open ports and the process and service names (sometimes with paths) that are holding them open
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Script: ShowListeners.ps1 | |
# Author: MotoX80 and Evgenij Smirnov on MS forums | |
# pmarreck note: If you get a security block, you may need to run the following first: | |
# Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process | |
# (or use CurrentUser for the -Scope if you want it to apply outside the current session, less secure though) | |
# For more, see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy?view=powershell-7.2 | |
$rpt = @() | |
$services = Get-CimInstance -Class Win32_Service -Filter 'State="Running"' | Select Name, ProcessID | |
$Listeners = Get-NetTCPConnection | Where-Object {$_.State -eq "Listen"} | |
foreach ($l in $Listeners){ | |
$proc = Get-Process -ID $l.OwningProcess | |
$rpt += [PSCustomObject]@{ | |
Port = $l.LocalPort | |
Pid = $l.OwningProcess | |
ProcessName = $proc.ProcessName | |
Service = (-join (($services.Where({$_.ProcessID -eq $l.OwningProcess})) | foreach {"$($_.name), "})).trimend(', ') | |
Path = $proc.Path | |
} | |
} | |
$rpt | Sort-Object -property Port | Format-Table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment