Skip to content

Instantly share code, notes, and snippets.

@davidlu1001
Created March 4, 2024 09:43
Show Gist options
  • Select an option

  • Save davidlu1001/2067fb5b12432fab32c2ee94258bc7ef to your computer and use it in GitHub Desktop.

Select an option

Save davidlu1001/2067fb5b12432fab32c2ee94258bc7ef to your computer and use it in GitHub Desktop.
Get Tcp Connections Info
param(
[switch]$ExportToCsv,
[string]$CsvPath = "C:\ports_info.csv"
)
function Get-TcpConnections {
try {
$connections = Get-NetTCPConnection
$processes = Get-Process
$result = foreach ($connection in $connections) {
$process = $processes | Where-Object { $_.Id -eq $connection.OwningProcess }
[PSCustomObject]@{
LocalAddress = $connection.LocalAddress
LocalPort = $connection.LocalPort
RemoteAddress = $connection.RemoteAddress
RemotePort = $connection.RemotePort
State = $connection.State
ProcessId = $connection.OwningProcess
ProcessName = if ($process) { $process.Name } else { "Unknown" }
}
}
} catch {
Write-Error "Failed to retrieve TCP connections. Error: $_"
return $null
}
return $result
}
$tcpConnections = Get-TcpConnections
if ($tcpConnections) {
if ($ExportToCsv) {
if (-not [string]::IsNullOrWhiteSpace($CsvPath)) {
try {
$tcpConnections | Export-Csv -Path $CsvPath -NoTypeInformation
Write-Host "TCP connections information exported to CSV file at $CsvPath"
} catch {
Write-Error "Failed to export TCP connections to CSV. Error: $_"
}
} else {
Write-Error "CSV path is empty or null. Provide a valid path for the CSV file."
}
} else {
$tcpConnections | Format-Table -AutoSize
}
} else {
Write-Host "No TCP connections information to display or export."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment