Skip to content

Instantly share code, notes, and snippets.

@yosignals
Last active December 23, 2022 14:41
Show Gist options
  • Save yosignals/5345ae1b82695a3d1b997504d3b0ab15 to your computer and use it in GitHub Desktop.
Save yosignals/5345ae1b82695a3d1b997504d3b0ab15 to your computer and use it in GitHub Desktop.
Netstat++
# Get the current date and time
$date = Get-Date
# Get a list of all open TCP connections
$tcpConnections = Get-NetTCPConnection
# Create a table to display the results
$table = New-Object System.Data.DataTable
$table.Columns.Add("Local Address")
$table.Columns.Add("Local Port")
$table.Columns.Add("Remote Address")
$table.Columns.Add("Remote Port")
$table.Columns.Add("State")
$table.Columns.Add("Process Name")
$table.Columns.Add("Process ID")
$table.Columns.Add("Process Start Time")
$table.Columns.Add("Process Owner")
$table.Columns.Add("Process Executable")
# Populate the table with the connection and process information
foreach ($connection in $tcpConnections) {
$row = $table.NewRow()
$row["Local Address"] = $connection.LocalAddress
$row["Local Port"] = $connection.LocalPort
$row["Remote Address"] = $connection.RemoteAddress
$row["Remote Port"] = $connection.RemotePort
$row["State"] = $connection.State
$process = Get-Process -Id $connection.OwningProcess
$row["Process Name"] = $process.Name
$row["Process ID"] = $connection.OwningProcess
$row["Process Start Time"] = $process.StartTime
$processOwner = Get-WmiObject -Class Win32_Process -Filter "ProcessId = $($connection.OwningProcess)" | Select-Object -ExpandProperty GetOwner
$row["Process Owner"] = "$($processOwner.Domain)\$($processOwner.User)"
$row["Process Executable"] = $process.MainModule.FileName
$table.Rows.Add($row)
}
# Generate a file name with a timestamp
$timestamp = $date.ToString("yyyy-MM-dd_HH-mm-ss")
$fileName = "OpenPorts_$timestamp.csv"
# Get the path to the current user's desktop
$desktop = [Environment]::GetFolderPath("Desktop")
# Save the table to a CSV file
$table | Export-Csv -NoTypeInformation -Path "$desktop\$fileName"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment