Logging TCP connection is useful for troubleshooting or for auditing purpose. You can use TCPView to view the real-time the incoming and outgoing TCP connections between servers and clients. To save the log into file, you need to use TCPLogView. But, the limitation is the duration of TCP capture, or based on log file size without actually doing the custom scripting. Windows has a built-in
netstat command which can capture the TCP/UDP connection. So, with the help of powershell, I loop the execution of
netstat command & capture the new TCP connection based on previous connections. With this script, you can capture new TCP connections to a specific time or until the log file size is reached to avoid the disk space consumption.
On my testing machine, I run the below command and it will capture the incoming/outgoing TCP connections for 90 minutes (See Fig-1).
.\Get-TcpLog.ps1 -min 1 -sec 30 -CsvFile | ft
Fig-1: Logging TCP Connections for 90 seconds