Files
powershell/Dennis_Scripts/Get-Connections.ps1
2023-03-09 09:06:25 +01:00

83 lines
2.9 KiB
PowerShell

function Get-Connections {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string[]]$Server
)
foreach($currentServer in $Server) {
#$ipaddresslist = [System.Net.Dns]::GetHostByName($server).AddressList | Select-Object -ExpandProperty IPAddressToString
Write-Verbose "Invoke-Command Get-WmiObject Win32_NetworkAdapterConfiguration"
$networkadapterconfiguration = Invoke-Command -ComputerName $currentServer -ScriptBlock { Get-WmiObject -Class Win32_NetworkAdapterConfiguration }
$ipaddresslist = foreach($adapter in $networkadapterconfiguration) {
if(-not $adapter.IPAddress) {
Write-Verbose "$($adapter.Description) IPAddress `$null"
continue
}
foreach($entry in $adapter.IPAddress) {
Write-Verbose "$($adapter.Description) IPAddress $entry"
Write-Output $entry
}
}
$ipaddresslist += '[::]','0.0.0.0','127.0.0.1'
Write-Verbose "Invoke-Command netstat -na"
$netstat = Invoke-Command -ComputerName $currentServer -ScriptBlock { netstat -na }
Write-Verbose "Result:`n$netstat"
foreach($line in $netstat) {
$str = $line.Trim() -replace " +", " "
Write-Verbose "Processing: $str"
if(-not $str.StartsWith("TCP")) {
Write-Verbose "'$str' is not TCP"
continue
}
$split = $str.Split(' ')
#[0] protocol
#[1] source:port
#[2] destination:port
#[3] state
if(-not $split[1].StartsWith('[')) { #IPv6
$source = $split[1].Split(':')
}
else {
$index = $split[1].IndexOf(']') + 1
$source = @(
$split[1].Substring(0, $index)
$split[1].Substring($index + 1)
)
}
#[0] ip
#[1] port
if(-not $split[2].StartsWith('[')) { #IPv6
$destination = $split[2].Split(':')
}
else {
$index = $split[1].IndexOf(']') + 1
$destination = @(
$split[2].Substring(0, $index)
$split[2].Substring($index + 1)
)
}
#[0] ip
#[1] port
Write-Output ([pscustomobject]@{
Server = $currentServer.ToUpper()
SourceIP = $source[0]
SourcePort = $source[1]
DestinationIP = $destination[0]
DestinationPort = $destination[1]
ServerIsSource = ($ipaddresslist -contains $source[0])
ServerIsDestination = ($ipaddresslist -contains $destination[0])
ConnectionState = $split[3]
})
}
}
}