
我有一個 PowerShell 腳本,其中有一些變數
$GetCon
:在Powershell中取得Tcp連接$hn
:取得擴充遠端位址$GetCon
。$rrt
: 是所有結果的編號,它是所有連線 IP。$GNamess
: 是一個變量,用於按名稱建立新成員 (網址)$GetCon
是一個 Get-NetTCPConnection。
最後我有一個新成員,它將包含 Get-TCPConnection RemoteAddress 中每個 IP 位址的每個連接主機名稱的清單。
但我們不會在結果中恢復主機的結果,在結果中,每個主機都有一個主機。
請給我一個方法來取得結果中的所有主機。
錯誤的語法:
$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