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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.