简体   繁体   English

Powershell 命令在 output 文件中没有包含错误

[英]Powershell command did not include error in output file

I have the code below, to be used in Powershell;我有下面的代码,用于 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.它表现良好,只是我需要 output 文件来包含 IP 未解析为名称时的错误消息。

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

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 .由于.GetHostEntry(..)没有给您关于哪个 IP 无法解析的明确提示,因此最好创建一个 object 将您尝试解析的 IP 地址与方法调用相关联。 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 .这还允许您拥有更好的导出类型,而不是普通的.txt文件,您可以使用Export-Csv将对象导出为.csv

Below example uses .GetHostEntryAsync(..) which allow us to query multiple hosts in parallel!下面的示例使用.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM