Get HostName for Each RemoteAddress IP in New Member
I have a PowerShell script, which has some variables
-
$GetCon
: Get Tcp Connection in Powershell -
$hn
: Get expand Remote-Address in$GetCon
. -
$rrt
: is a Number of all results, it's all connection IP's. -
$GNamess
: is a variable to Create a new Member by name (urls) for$GetCon
which is a Get-NetTCPConnection.
Finally I have a new member, it will be contain list of each Connections Host Names for Each IP Address in Get-TCPConnection RemoteAddress.
But we don't revive result of host's in the result, in the result I've one Host for each host's.
please get me an method to get all host's in the result.
Wrong Syntax:
$GetCon = Get-NetTCPConnection
$hn = $GetCon | select -expand RemoteAddress
$rrt = foreach ($IPs in $hn)
{
[System.Net.Dns]::GetHostAddresses($IPs) | select-object IPAddressToString -expandproperty IPAddressToString
}
$GNamess = foreach ($IPst in $GetCon) {
$rrt = ([System.Net.Dns]::GetHostbyAddress($IPs) | select-object HostName -expandproperty HostName)
$IPst | Add-Member -NotePropertyName urls -NotePropertyValue $rrt -PassThru
}
$GetCon | select urls
Image Result: Image Result
Solution 1:
Too long for comment and hard to guess your aim from your code so maybe creating an filling dictionary $IPsNames
could help?
$IPsNames = @{}
$GetCon = Get-NetTCPConnection
$hn = $GetCon | select -expand RemoteAddress | sort -Unique
foreach ( $IPs in $hn ) {
try { $rrtx = [System.Net.Dns]::GetHostbyAddress($IPs).HostName }
catch { $rrtx = '???' }
$IPsNames[ $IPS ] = $rrtx
}
### $IPsNames
for ( $i = 0; $i -lt $GetCon.Count; $i++ ) {
$aux = $IPsNames[ $GetCon[$i].RemoteAddress ]
$GetCon[$i] | Add-Member -NotePropertyName urls -NotePropertyValue $aux
}
### $GetCon | Format-Table -Property RemoteAddress, urls -AutoSize
$GetCon | selelect -Property RemoteAddress, urls