powershell-使用多个IP解析DNS地址

我目前正在尝试获取一个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

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

谢谢!

最佳答案
CSV不了解Array的对象,仅了解纯文本.

您可以在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

转载注明原文:powershell-使用多个IP解析DNS地址 - 代码日志