Powershell – Bound Ports Logging

This script provides 2 functionalities:

  • Log the process with the most bound ports along with the number of ports linked to that process, plus a timestamp
  • Log the output of a command to list processes with bound ports, plus a timestamp

The first bullet is the star of the show, but the second is helpful as a backup, just to make sure you’re pulling the correct data.  Here’s what the 2 files look like:

				
					$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logFile = "C:\_Logs\BoundPorts_output_log.txt"
$csvFile = "C:\_Logs\BoundPorts_highest.csv"

# Check if log file exists, if not create it
if (-not (Test-Path -Path $logFile)) {
    New-Item -ItemType File -Path $logFile | Out-Null
}

# Check if CSV file exists, if not create it and add header row
if (-not (Test-Path -Path $csvFile)) {
    $header = "Timestamp,Count,Name,ProcessName"
    $header | Out-File -FilePath $csvFile -Encoding utf8
}

# Run command and select first row of results
$output = Get-NetTCPConnection | Group-Object -Property State, OwningProcess | Select -Property Count, Name, @{Name="ProcessName";Expression={(Get-Process -PID ($_.Name.Split(',')[-1].Trim(' '))).Name}}, Group | Where-Object -Property Name -Match "bound" | sort -Property count -Descending

$row = $output[0]
$props = @{
    Timestamp = $timestamp
    Count = $row.Count
    Name = $row.Name
    ProcessName = $row.ProcessName
}

# Write output to log file
"$timestamp $($output | Out-String)" | Out-File $logFile -Append

# Write output to CSV file
New-Object -TypeName PSObject -Property $props | Export-Csv -Path $csvFile -Append -NoTypeInformation