Search code examples
powershell

How to redirect only the powershell output without errors to a file


Need help in a powershell script . My code

foreach($line in Get-Content C:\Users\G661600\Downloads\sublist.txt) { 
[System.Net.Dns]::GetHostAddresses("$line") | select IPAddressToString }

This gives me the IP addresses of domains contained in sublist.txt. Sublist.txt also contains some domains which donot resolve to any IP. If I redirect this output to a file it also contains the errors (for the domains which don't resolve)

My query is

  1. How to get get the domain names against the IP addresses
  2. How to get only the output omitting the errors from the output file

Solution

  • This work by me:

    $Adresses=("www.google.com","www.bing.com","domain.without.ip")
    
    $Adresslist = @{}
    
    foreach($line in $Adresses) { 
        $result = try {[System.Net.Dns]::GetHostAddresses("$line")}
        catch {}
        $index = 0
        Foreach ($IP in ($result| select IPAddressToString)){
            
            $Null= $Adresslist.Add("[$index]$line", $IP.IPAddressToString)
            $index++
    
        }
    
    }
    
    $Adresslist