Hello and thanks to anyone in advance who can help.
I am trying to write a powershell script that gets a list of all connections to a server containing a certain keyphrase and outputs the DNS names and corresponding IPs to a csv file.
I have run into some typing issues. This is my code for an attempt with NetTCPConnection:
# get remote addrs
$a = (Get-NetTCPConnection | Select-Object RemoteAddress)
# get IPs of valid addrs
Workflow Get-DNSNames([string[]]$IPAddresses){
foreach -parallel ($IP in $IPAddresses | Select-Object -Unique){
# $IP.ToString()
[system.net.dns]::GetHostEntry($IP)).hostname
try{
@{$IP = $(([system.net.dns]::GetHostEntry($IP)).hostname)}
}catch{
@{$IP = "N/A"}
}
}
}
# output to txt
$List = Get-DNSNames -IPAddresses $a
$List | Out-File "C:\temp\getBAS\IPAddresses_Complete.txt"
And this is my attempt with netstat:
# get netstat output
$a = netstat
$b = $a[3..$a.count] | ConvertFrom-string | Select p4 | Where p4 -like "*52*"
# get IP and create name, IP pairs
$c = @()
foreach ($DNS in $b) {
# name , IP
$rowToAdd = New-Object psobject
$name = $DNS
$IP = [System.Net.Dns]::GetHostAddresses($DNS.ToString())
$rowToAdd | Add-Member -Member NoteProperty -Name "Name" -value $name
$rowToAdd | Add-Member -Member NoteProperty -Name "IP" -value $IP
$c += $rowToAdd
}
$c
# output to csv
$final | Export-Csv -Path "C:\temp\getBAS\NetworkConnectionsBAS.csv" -NoTypeInformation
The problem with the first attempt is that the values from NetTCPConnection are objects, not strings, and strings are needed in the GetHost function. I could not figure out a way to convert each individual addr object to a string.
The problem with my second attempt is that I get a wacky csv output.
I am frankly stuck and would appreciate any help. Thanks
$a = (Get-NetTCPConnection | Select-Object RemoteAddress)
This is making $a an object with the RemoteAddress property in it, you aren't converting this to a string anywhere that I can see.
You can either change this line to
$a = (Get-NetTCPConnection | Select-Object -ExpandProperty RemoteAddress)
to get a String containing the value of RemoteAddress
or change
$List = Get-DNSNames -IPAddresses $a
to
$List = Get-DNSNames -IPAddresses "$($a.RemoteAddress)"
this will pull just the value from the property which should then be treated as a string.