Created
November 27, 2025 22:31
-
-
Save SweetAsNZ/db818892ca53f03161fb9722630dd9cf to your computer and use it in GitHub Desktop.
Retrieves a list of listening TCP and UDP ports along with their associated process names analogous to "netstat -anob"
This file contains hidden or 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
| function Get-ListeningPorts { | |
| <# | |
| .SYNOPSIS | |
| Retrieves a list of listening TCP and UDP ports along with their associated process names. | |
| .DESCRIPTION | |
| This function fetches all listening TCP and UDP ports on the local machine and displays them along | |
| with the names of the processes that own those ports. An optional parameter allows filtering out IPv6 addresses. | |
| .PARAMETER NotIPv6 | |
| If specified, the function will exclude IPv6 addresses from the results. | |
| .EXAMPLE | |
| Get-ListeningPorts -NotIPv6 | |
| .NOTES | |
| Author: Tim West | |
| Company: Air New Zealand | |
| Created: 2025-11-28 | |
| Status: Production | |
| Version: 1.0 | |
| #> | |
| [CmdletBinding()] | |
| param( | |
| [switch]$NotIPv6 | |
| ) | |
| $tcp = Get-NetTCPConnection -State Listen | |
| $udp = Get-NetUDPEndpoint | |
| $results = $tcp + $udp | ForEach-Object { | |
| $p = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | |
| [PSCustomObject]@{ | |
| Protocol = if ($_ -is [Microsoft.Management.Infrastructure.CimInstance] -and $_.PSObject.TypeNames[0] -like "*TCP*") {"TCP"} else {"UDP"} | |
| LocalAddress = $_.LocalAddress | |
| LocalPort = $_.LocalPort | |
| ProcessName = $p.Name | |
| } | |
| } | |
| if ($NotIPv6) { | |
| $results | Where-Object { $_.LocalAddress -notlike ":" } | Sort-Object Protocol,LocalPort | |
| } | |
| else { | |
| $results | Sort-Object Protocol,LocalPort | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment