【问题标题】:Custom Foreach loop nslookup export to csv自定义 Foreach 循环 nslookup 导出到 csv
【发布时间】:2017-09-14 07:31:36
【问题描述】:

我是 PowerShell 脚本的新手。我正在尝试制作一个脚本,将 DNS 名称列表解析为其 IP,并将它们作为 CSV 文件输出。当服务器无法解析时,应将其输出到单独的文件中。

这是我的代码:

$location
$location = Read-Host "CSV Path: "
$Names = Import-Csv -Path $location

foreach($n in $Names)
{
    try 
    {
        $output = $n.NAME
        $variable1 = [system.net.dns]::resolve($output) | Select 
        HostName,AddressList 
        $variable1
        $IP = $variable1.AddressList | Select-Object IPAddressToString
        $IPN = $IP.IPAddressToString
        $csv+=New-Object psobject -Property @{IPAddresse= $IPN;Name= 
        $output} | 
        Export-Csv \\filepath\Working.csv -NoTypeInformation
     }

    catch 
    {
        Write-host "$output is unreachable."
        Write-Output "$output" | Export-Csv \\Filepath\Unreachable.csv -
        Append -Encoding ASCII
    }

}

编辑:代码运行良好,但现在它说导入时存在分隔符错误,但我不知道为什么会突然出现这种情况,因为代码工作没有得到任何编辑,突然不再工作了

【问题讨论】:

  • 欢迎来到 StackOverflow。如果您解释了您现有的解决方案不起作用的方式,它可能会对我们有所帮助。当您遇到可以重现的特定问题时,SO 效果最佳。
  • 在快速扫描中,我可以看到您正在使用一个名为 $ausgabe 的变量,它永远不会填充任何值。此外,您使用 $csv 作为数组,但尚未将其定义为数组(也填充此变量似乎是多余的)。
  • @MarkWragg 这是一个翻译错误以使其为社区所接受

标签: powershell csv foreach export nslookup


【解决方案1】:

这是您的代码的简化/更正版本:

$location = Read-Host "CSV Path: "
$Names = Import-Csv -Path $location

foreach($n in $Names)
{
    try {
        $Computer = [system.net.dns]::resolve($n.NAME) | Select HostName,AddressList 
        $IP = ($Computer.AddressList).IPAddressToString
        New-Object PSObject -Property @{IPAddress=$IP; Name=$Computer.HostName} | Export-Csv \\filepath\Working.csv -NoTypeInformation -Append
    } catch {
        Write-Host "$($n.NAME) is unreachable."
        Write-Output $n | Export-Csv \\Filepath\Unreachable.csv -Append -Encoding ASCII
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-05
    • 2016-03-13
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2016-07-11
    • 2013-08-06
    相关资源
    最近更新 更多