我有一个 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