在测试连接中解析 DnsName

Resolve-DnsName inside Test-Connection

我想知道如何 return 我的 Test-Connection 脚本的 Resolve-DnsName 输出并将其添加到我创建的 CSV 文件中。

我想从中获取名称、类型、TTL、部分。

仅在 ping 不成功时调用 Resolve-DnsName

$servers = Get-Content "servers.txt"
$collection = $()
foreach ($server in $servers)
{
    $status = @{ "ServerName" = $server; "TimeStamp" = (Get-Date -f s) }
    $result = Test-Connection $server -Count 1 -ErrorAction SilentlyContinue
    if ($result)
    {
        $status.Results = "Up"
        $status.IP =  ($result.IPV4Address).IPAddressToString
    }
    else
    {
        $status.Results = "Down"
        $status.IP = "N/A"
        $status.DNS = if (-not(Resolve-DnsName -Name $server -ErrorAction SilentlyContinue))
        {
            Write-Output -Verbose "$server -- Not Resolving"
        }
        else
        {
            "$server resolving"
        }
    }
    New-Object -TypeName PSObject -Property $status -OutVariable serverStatus

    $collection += $serverStatus
}
$collection | Export-Csv -LiteralPath .\ServerStatus3.csv -NoTypeInformation

但 CSV 中没有添加任何新内容。

您 运行 遇到了 PowerShell 问题。 PowerShell 确定第一个处理对象的 tabular/CSV 输出中显示的列。如果该对象没有 属性 DNS 该列将不会显示在输出中,即使列表中的其他对象确实有它。如果其他对象没有第一个对象中存在的属性,它们将显示为空值。

示范:

PS C:\> $a = (New-Object -Type PSObject -Property @{'a'=1; 'b'=2}),
>> (New-Object -Type PSObject -Property @{'a'=3; 'b'=4; 'c'=5}),
>> (New-Object -Type PSObject -Property @{'b'=6; 'c'=7})
>>
PS C:\> $a | Format-Table -AutoSize

a b
- -
1 2
3 4
  6

PS C:\> $a[1..2] | Format-Table -AutoSize

c b a
- - -
5 4 3
7 6

如果你想生成表格输出总是用相同的属性集创建你的对象。选择合理的默认值甚至可以让您减少整个代码库。

$collection = foreach ($server in $servers) {
  $status = New-Object -Type PSObject -Property @{
    'ServerName' = $server
    'TimeStamp'  = Get-Date -f s
    'Results'    = 'Down'
    'IP'         = 'N/A'
    'HasDNS'     = [bool](Resolve-DnsName -Name $server -EA SilentlyContinue)
  }

  $result = Test-Connection $server -Count 1 -EA SilentlyContinue

  if ($result) {
    $status.Results = 'Up'
    $status.IP      =  ($result.IPV4Address).IPAddressToString
  }

  $status
}