使用多个IP解析DNS地址

问题描述 投票:3回答:1

我目前正在尝试获取一个CSV文件,该文件显示域的IP地址和域本身。我会手动执行此操作,但我正在测试接近1K域名。

这是我目前的代码:

$Domains = Get-Content "X:\User\URLs.txt"
$collection = $()

foreach($Domain in $Domains)
   {
    Write-Host "Testing $Domain"
    $status = @{ "Domain" = $Domain}
    $result = [system.net.dns]::GetHostAddresses($Domain)

    if($result)
    {
        $status.Results = "UP"
        $status.IP = [system.net.dns]::GetHostAddresses($Domain).IPAddressToString
        Write-Host "GOOD"        
    }#END If

    else
    {
        $status.Results = "Down"
        $status.IP = "N/A"
        $status.DNS = if (-not(Resolve-DnsName -Name $Domain -ErrorAction SilentlyContinue))
        {
         Write-Output -Verbose "$Domain -- Not Resolving"
        }#END inner if

        else
        {
        "$Domain resolving"
        }#END inner else

    }#END else

    New-Object -TypeName PSObject -Property $status -OutVariable domainStatus
    $collection += $domainStatus

}#END forEach
$collection | Export-Csv -LiteralPath "X:\User\DomainList.csv" -Append -Force

我遇到的问题是某些域有超过1个IP地址,当我打开CSV文件时,我得到一个System.Object[]用于具有1个以上IP的域。在大多数情况下,我使用Resolve-DnsName inside Test-Connection来创建此代码,但问题是当有超过1个IP时。

谢谢!

powershell csv dns ip
1个回答
3
投票

CSV不了解数组的对象,只有纯文本。

您可以在Export-CSV cmdlet之前使用逗号(或任何其他字符)加入IP(如果多于一个),如下所示:

$Collection | Select Domain,@{N="IP";E={$_.IP -join ','} },Results |
Export-Csv -LiteralPath "X:\User\DomainList.csv" -Append -Force

另一个选项是为每个IP添加另一行,但您需要稍微修改一下代码:

$Domains = 'google.com','microsoft.com' 
$Collection = @()

foreach ($Domain in $Domains)
{
    Write-Host "Testing $Domain"

    Try {

        foreach ($IP in [system.net.dns]::GetHostAddresses($Domain).IPAddressToString)
        {
        $Row = "" | Select Domain,IP,Status
        $Row.Domain = $Domain
        $Row.IP = $IP
        $Row.Status = "UP"
        $Collection += $Row
        }
    }

    Catch 
    {
        $Row = "" | Select Domain,IP,Status
        $Row.Domain = $Domain
        $Row.Status = "DOWN"
        $Collection += $Row
    }
}

$Collection | Export-Csv -LiteralPath "X:\User\DomainList.csv" -Append -Force
© www.soinside.com 2019 - 2024. All rights reserved.