Home > Software engineering >  Powershell command did not include error in output file
Powershell command did not include error in output file

Time:05-02

I have the code below, to be used in Powershell; it performed well, except that I need the output file to also include the error messages whenever the IPs did not resolve to names.

Get-Content inputfile.txt | 
    foreach-object { [System.Net.Dns]::GetHostEntry($_)  } | 
    out-file -filepath outputfile.txt

At the moment, I'm able to see the red error messages displayed on Powershell window. But I want these to appear in the output file along with the results for each item listed in the input file.

Thanks in advance!

CodePudding user response:

Since .GetHostEntry(..) doesn't give you a clear hint as to which IP failed to be resolved it's better if you create an object that associates the IP Address you're trying to resolve with the method call. This also allows you to have a better export type, instead of plain .txt file, you can export your objects as .csv with Export-Csv.

Below example uses .GetHostEntryAsync(..) which allow us to query multiple hosts in parallel!

using namespace System.Collections.Generic
using namespace System.Collections.Specialized

(Get-Content inputfile.txt).ForEach{
    begin { $tasks = [List[OrderedDictionary]]::new() }
    process {
        $tasks.Add([ordered]@{
            Input    = $_
            Hostname = [System.Net.Dns]::GetHostEntryAsync($_)
        })
    }
    end {
        do {
            $id = [System.Threading.Tasks.Task]::WaitAny($tasks.Hostname, 200)
            if($id -eq -1) { continue }
            $thisTask = $tasks[$id]
            $thisTask['Hostname'] = try {
                $thisTask.Hostname.GetAwaiter().GetResult().HostName
            }
            catch { $_.Exception.Message }
            $tasks.RemoveAt($id)
            [pscustomobject] $thisTask
        } while($tasks)
    }
} | Export-Csv outputfile.csv -NoTypeInformation
  • Related