
У меня есть скрипт PowerShell, в котором есть несколько переменных
$GetCon
: Получить TCP-соединение в Powershell$hn
: Получить развернутый Remote-Address в$GetCon
.$rrt
: это число всех результатов, это все IP-адреса подключений.$GNamess
: это переменная для создания нового члена по имени (URL-адреса) для$GetCon
которого есть Get-NetTCPConnection.
ОкончательноУ меня есть новый участник, он будет содержать список имен хостов каждого подключения для каждого IP-адреса в Get-TCPConnection RemoteAddress.
Номы не оживляем результат хостов в результате, в результате у меня есть один Хост для каждого хоста.
пожалуйста, дайте мне метод, чтобы получить все хосты в результате.
Неправильный синтаксис:
$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
Результат изображения: Результат изображения
решение1
Слишком длинно для комментариев и сложно угадать вашу цель по коду, так что, может быть, создание заполняющего словаря $IPsNames
поможет?
$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
решение2
<# Report = LocalAddress,LocalPort,RemoteAddress,FQDN,RemotePort,PID,ProcessName,UserName,State,CreationTime #>
$obj=@()
Foreach($p In (Get-Process -IncludeUserName | where {$_.UserName} | `
select Id, ProcessName, UserName)) {
$properties = @{ 'PID'=$p.Id;
'ProcessName'=$p.ProcessName;
'UserName'=$p.UserName;
}
$psobj = New-Object -TypeName psobject -Property $properties
$obj+=$psobj
}
$Connections = Get-NetTCPConnection | where {$_.State -ne "Listen" -and $_.State -ne "Bound"} | select `
LocalAddress, `
LocalPort, `
RemoteAddress, `
@{name='FQDN';expression={ (Resolve-DnsName -name $_.Remoteaddress).NameHost}},`
RemotePort, `
@{n="PID";e={$_.OwningProcess}}, @{n="ProcessName";e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty ProcessName)}}, `
@{n="UserName";e={($obj |? PID -eq $_.OwningProcess | select -ExpandProperty UserName)}}, `
"State","CreationTime"|
sort -Property ProcessName, UserName
$Report += $Connections
$Connections=@()
$Reported = $Report | Sort-Object -Property * -Unique
$Report = $Reported
$Report |Export-Csv -Path C:\PATH\Connections.csv