【问题标题】:Resolve-DnsName inside Test-ConnectionTest-Connection 中的 Resolve-DnsName
【发布时间】:2016-04-13 17:57:59
【问题描述】:

我想知道如何从 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 添加任何新内容。

【问题讨论】:

  • 不要假设。尝试。如果失败:回来并展示您尝试过的内容以及获得的结果。
  • 如果没有添加任何内容,我怀疑该名称确实可以解析。在该语句中添加一个else 分支以确保:$status.DNS = if (...) {...} else {"$server resolving"}
  • 我试过了,什么都没有写出来。请问还有什么建议吗?

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

您遇到了 PowerShell 问题。 PowerShell 从处理的第一个对象确定表格/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 |格式表-AutoSize

一个
- -
1 2
3 4
  6

PS C:\> $a[1..2] |格式表-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
}

【讨论】:

  • 非常感谢您。一般问题,如果我想遍历结果并获取例如类型、TTL 和部分?是否以某种方式记录了如何检索这些内容?
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多