I have a nice Netstat script that I modified from http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2011/02/10/How-to-find-running-processes-and-their-port-number.aspx
I want to add an extra column so instead of this:
Protocol LocalAddress LocalPort RemoteAddress
TCP 0.0.0.0 135 0.0.0.0
TCP 0.0.0.0 32111 0.0.0.0
TCP 0.0.0.0 3389 0.0.0.0
I want do add additional fields that aren't part of the query like todays date and computername because I will be importing this into SQL
Date ComputerName Protocol LocalAddress LocalPort RemoteAddress
20130507 Computer1 TCP 0.0.0.0 135 0.0.0.0
20130507 Computer1 TCP 0.0.0.0 32111 0.0.0.0
20130507 Computer1 TCP 0.0.0.0 3389 0.0.0.0
The current code I use is below:
function Get-NetworkStatistics
{
$properties = 'Protocol','LocalAddress','LocalPort'
$properties += 'RemoteAddress','RemotePort','State','ProcessName'
netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
$item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::')
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else
{
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else
{
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
New-Object PSObject -Property @{
ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
} | Select-Object -Property $properties
}
}
}
Get-NetworkStatistics |
Where {$_.State -eq 'LISTENING' -or $_.State -eq 'ESTABLISHED' -or $_.Protocol -eq 'UDP'} | Sort Protocol,LocalAddress,LocalPort |`
Format-Table -Property Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,@{Label='PortState';Expression={$_.State}},ProcessName -AutoSize
So is it possible to add additional fields to the output that aren't part of the main query and how?