Here is a little script that can turn the output of netstat -ano
into objects
switch -Regex (netstat -ano){
'TCP' {
, -split $_ | ForEach-Object {
$localaddr,$localport = -split ($_[1] -replace '(^.+):(.+$)','$1 $2')
$remoteaddr,$remoteport = -split ($_[2] -replace '(^.+):(.+$)','$1 $2')
[PSCustomObject]@{
Protocol = $_[0]
LocalAddress = $localaddr
LocalPort = $localport
RemoteAddress = $remoteaddr
RemotePort = $remoteport
ProcessID = $_[4]
State = $_[3]
}
}
}
'UDP' {
, -split $_ | ForEach-Object {
$localaddr,$localport = -split ($_[1] -replace '(^.+):(.+$)','$1 $2')
$remoteaddr,$remoteport = -split ($_[2] -replace '(^.+):(.+$)','$1 $2')
[PSCustomObject]@{
Protocol = $_[0]
LocalAddress = $localaddr
LocalPort = $localport
RemoteAddress = $remoteaddr
RemotePort = $remoteport
ProcessID = $_[3]
State = 'Stateless'
}
}
}
}
You can assign the output of it to a variable and then convert/export that variable to Csv, or in the case of running on a remote machine like you've shown here using Invoke-Command
you can use the following
$data = Invoke-Command -ComputerName Win10-Admin -Scriptblock {
switch -Regex (netstat -ano){
'TCP' {
, -split $_ | ForEach-Object {
$localaddr,$localport = -split ($_[1] -replace '(^.+):(.+$)','$1 $2')
$remoteaddr,$remoteport = -split ($_[2] -replace '(^.+):(.+$)','$1 $2')
[PSCustomObject]@{
Protocol = $_[0]
LocalAddress = $localaddr
LocalPort = $localport
RemoteAddress = $remoteaddr
RemotePort = $remoteport
ProcessID = $_[4]
State = $_[3]
}
}
}
'UDP' {
, -split $_ | ForEach-Object {
$localaddr,$localport = -split ($_[1] -replace '(^.+):(.+$)','$1 $2')
$remoteaddr,$remoteport = -split ($_[2] -replace '(^.+):(.+$)','$1 $2')
[PSCustomObject]@{
Protocol = $_[0]
LocalAddress = $localaddr
LocalPort = $localport
RemoteAddress = $remoteaddr
RemotePort = $remoteport
ProcessID = $_[3]
State = 'Stateless'
}
}
}
}
} -HideComputerName | Select-Object -Property * -ExcludeProperty RunSpaceId
$data | ConvertTo-Csv -NoTypeInformation