Reputation: 83
I'm using this Get-ADComputer script to find machines in a specific OU. Now I need to capture the inbound and outbound ports of machines in the script's output. I know this could be done with netstat, but I'm not sure how to include this in the script below. Any feedback would be much appreciated.
# Enter CSV file location
$csv = "C:\MyLocation"
# Add the target OU in the SearchBase parameter
$Computers = Get-ADComputer -Filter * -SearchBase "OU=xxx,OU=xx,OU=xx,OU=_xx,DC=xx,DC=xxx,DC=com" | Select Name | Sort-Object Name
$Computers = $Computers.Name
$Headers = "ComputerName,IP Address"
$Headers | Out-File -FilePath $csv -Encoding UTF8
foreach ($computer in $Computers)
{
Write-host "Pinging $Computer"
$Test = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue -ErrorVariable Err
if ($test -ne $null)
{
$IP = $Test.IPV4Address.IPAddressToString
$Output = "$Computer,$IP"
$Output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
Else
{
$Output = "$Computer,$Err"
$output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
cls
}
Upvotes: 0
Views: 170
Reputation: 25001
You can use Get-NetTCPConnection to return TCP connections as a PowerShell object collection.
$netstat = Get-NetTCPConnection
$listeningPorts = $netstat | where state -eq 'Listen' | select -expand localport -unique
$netstat | where {$_.LocalPort -and $_.RemotePort -and $_.LocalAddress -ne '127.0.0.1'} |
Select LocalAddress,LocalPort,RemoteAddress,RemotePort,
@{n='Direction';e={
if ($_.LocalPort -in $listeningPorts) {
'Inbound'
}
else { 'Outbound' }
}
}
If you want to run this remotely, provided you have PSRemoting enabled, you can utilize Invoke-Command:
$sb = {
$netstat = Get-NetTCPConnection
$listeningPorts = $netstat | where state -eq 'Listen' | select -expand localport -unique
$netstat | where {$_.LocalPort -and $_.RemotePort -and $_.LocalAddress -ne '127.0.0.1'} |
Select LocalAddress,LocalPort,RemoteAddress,RemotePort,
@{n='Direction';e={
if ($_.LocalPort -in $listeningPorts) {
'Inbound'
}
else { 'Outbound' }
}
}
}
Invoke-Command -ComputerName $Computers -Scriptblock $sb
The Where
criteria may need to change. My assumptions were to not include any ports numbered 0
or any connections made by 127.0.0.1
. Once listening ports are established, I assume they are used in inbound connections only.
Upvotes: 1