
PowerShellスクリプトにはいくつかの変数があります
$GetCon
: Powershell で TCP 接続を取得する$hn
: で展開されたリモート アドレスを取得します$GetCon
。$rrt
: はすべての結果の数であり、すべての接続 IP です。$GNamess
: 名前で新しいメンバーを作成する変数です(URL) に対する$GetCon
Get-NetTCPConnection です。
ついに新しいメンバーができました。Get-TCPConnection RemoteAddress には、各 IP アドレスの各接続ホスト名のリストが含まれます。
しかし結果ではホストの結果を復活させません。結果では、ホストごとに 1 つのホストがあります。
結果内のすべてのホストを取得する方法を教えてください。
間違った構文:
$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