Skip to content

Instantly share code, notes, and snippets.

@sannae
Created August 19, 2021 15:05
Show Gist options
  • Save sannae/d0db127dfa6a28c2ac4a4b4dd885e15c to your computer and use it in GitHub Desktop.
Save sannae/d0db127dfa6a28c2ac4a4b4dd885e15c to your computer and use it in GitHub Desktop.
PowerShell function to get the list of active connections, grouped or not
<#
.SYNOPSIS
It produces a list of the active connections and outputs to a file.
.DESCRIPTION
The script basically calls the Get-NetTcpConnection cmdlet to have a picture of the active connections.
Each connection is retrieved with all the details about the owning process.
The $Grouped switch let you group the results and sort them descending by amount of active connections.
The amount of free dynamic ports and the OS uptime are also printed.
.PARAMETER DESTINATIONFILEPATH
String containing the output file path.
Its existence will be checked.
.PARAMETER GROUPED
Switch to define the results as simply listed or grouped.
.NOTES
TODO: Check if the script is ran as administrator
.NOTES
https://serverfault.com/questions/963140/what-are-sockets-with-bound-state-on-0-0-0-0
#>
function Get-NetstatProcess {
[CmdletBinding()]
param (
[Parameter(Mandatory=$True, HelpMessage="Output file destination path")]
[ValidateScript({Test-Path $_ })]
[string]$DestinationFilePath,
[switch]$Grouped
)
# Variables
$RightNow = Get-Date -Format "yyyyMMdd_HHmm"
if ($Grouped) {
$OutputFile = "$RightNow" + "_Netstat_grouped.log"
} else {
$OutputFile = "$RightNow" + "_Netstat_all_processes.log"
}
# Date
Get-Date -Format "dd-MM-yyyy HH:mm" | Out-file "$DestinationFilePath\$OutputFile" -Append
# Uptime
$SinceLastBoot = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUptime
$TotalTime = "Uptime : " + $SinceLastBoot.Days.ToString() + " days, " + $SinceLastBoot.Hours.ToString() + " hours"
$TotalTime | Out-file "$DestinationFilePath\$OutputFile" -Append
# Connections
$Connections = Get-NetTCPConnection | Select-Object -property LocalAddress, LocalPort, RemoteAddress, RemotePort, State, @{Name = "PID"; Expression = { $_.OwningProcess } }, @{Name = "ProcessName"; Expression = { $(Get-Process -id $_.OwningProcess).Name } }, @{Name = "ProcessPath"; Expression = { $(Get-Process -id $_.OwningProcess).Path } }, @{Name = "HandleCount"; Expression = { $(Get-Process -id $_.OwningProcess).HandleCount } }
# Format output
if ($Grouped) {
$GroupedConnections = $Connections | Group-Object -Property PID,State | Select-Object -Property Count,@{Name="State";Expression={($_.Name.Split(',')[1])}}, @{Name="ProcessID";Expression={($_.Name.Split(',')[0])}}, @{Name = "HandleCount"; Expression = { (Get-Process -PID ($_.Name.Split(',')[0].Trim(' '))).HandleCount } }, @{Name="ProcessName";Expression={(Get-Process -PID ($_.Name.Split(',')[0].Trim(' '))).Name}}, @{Name = "ProcessPath"; Expression = { (Get-Process -PID ($_.Name.Split(',')[0].Trim(' '))).Path } }
$GroupedConnections | Sort-Object Count -Descending | Format-Table -Property Count, State, ProcessID, ProcessName, @{ Expression='ProcessPath'; width = 255 }, HandleCount | Out-file "$DestinationFilePath\$OutputFile" -Append
$OccupiedPorts = $GroupedConnections | Measure-Object -Property Count -Sum | Select-Object -ExpandProperty Sum
} else {
$Connections | Format-Table -Autosize -Property LocalAddress, LocalPort, RemoteAddress, RemotePort, State, PID, HandleCount, ProcessName, @{ Expression='ProcessPath'; width = 255 } | Out-file "$DestinationFilePath\$OutputFile" -Append
}
# Available ports
$DynamicPorts = Get-NetTcpSetting | Select-Object -Property SettingName, @{Name="InitialPort"; Expression={$_.DynamicPortRangeStartPort}}, @{Name="AvailablePorts";Expression={$_.DynamicPortRangeNumberOfPorts}} | Where-Object {$_.SettingName -eq 'Internet'}
$RemainingPorts = "Available dynamic ports: " + $($DynamicPorts.AvailablePorts - $OccupiedPorts)
$RemainingPorts | Out-File "$DestinationFilePath\$OutputFile" -Append
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment