自定义Foreach循环nslookup导出到csv

时间:2017-09-14 07:31:37

标签: powershell csv foreach export nslookup

我是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
    }

}

编辑:代码工作得很好,但现在它说导入有分隔符错误,但我不知道为什么这突然出现,因为代码工作没有任何编辑,突然不再工作

1 个答案:

答案 0 :(得分: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
    }
}