Powershell 命令未在输出文件中包含错误

Powershell command did not include error in output file

我有下面的代码,可以在Powershell中使用;它表现良好,除了我需要输出文件还包含 IP 未解析为名称时的错误消息。

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

目前,我可以看到 Powershell window 上显示的红色错误消息。但我希望这些与输入文件中列出的每个项目的结果一起出现在输出文件中。

提前致谢!

.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.

下面的示例使用 .GetHostEntryAsync(..) 允许我们并行查询多个主机!

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