Skip to content

Instantly share code, notes, and snippets.

@SweetAsNZ
Created November 27, 2025 22:31
Show Gist options
  • Select an option

  • Save SweetAsNZ/db818892ca53f03161fb9722630dd9cf to your computer and use it in GitHub Desktop.

Select an option

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"
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