title: Powershell Convert NetTCPConnection or netstat To String
body: <p>Hello and thanks to anyone in advance who can help.</p>
  <p>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.</p>
  <p>I have run into some typing issues. This is my code for an attempt with NetTCPConnection:</p>
  <pre><code># 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 = &quot;N/A&quot;}
          }
      }
  }
  
  # output to txt
  $List = Get-DNSNames -IPAddresses $a
  $List | Out-File &quot;C:\temp\getBAS\IPAddresses_Complete.txt&quot;
  </code></pre>
  <p>And this is my attempt with netstat:</p>
  <pre><code># get netstat output
  $a = netstat
  
  $b = $a[3..$a.count] | ConvertFrom-string | Select p4 | Where p4 -like &quot;*52*&quot;
  
  # 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 &quot;Name&quot; -value $name
      $rowToAdd | Add-Member -Member NoteProperty -Name &quot;IP&quot; -value $IP
      $c += $rowToAdd
  }
  $c
  
  # output to csv
  $final | Export-Csv -Path &quot;C:\temp\getBAS\NetworkConnectionsBAS.csv&quot; -NoTypeInformation
  </code></pre>
  <p>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.</p>
  <p>The problem with my second attempt is that I get a wacky csv output.</p>
  <p>I am frankly stuck and would appreciate any help. Thanks</p>