$null, $null, $null, $null, $netstat = netstat -a -n -o [regex]$regexTCP = '(?\S+)\s+((?(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?\d+)\s+((?(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?\d+)\s+(?\w+)\s+(?\d+$)' [regex]$regexUDP = '(?\S+)\s+((?(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?))|(?\[?[0-9a-fA-f]{0,4}(\:([0-9a-fA-f]{0,4})){1,7}\%?\d?\]))\:(?\d+)\s+(?\*)\:(?\*)\s+(?\d+)' [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName foreach ($net in $netstat) { switch -regex ($net.Trim()) { $regexTCP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } $regexUDP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } } $process }