我目前正在尝试获取一个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时。
谢谢!
答案 0 :(得分: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