powershell - 测试连接内解析 DnsName

标签 powershell powershell-2.0 powershell-3.0

我想知道如何从我的 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 确定第一个处理的对象的表格/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

If you want to generate tabular output always create your objects uniformly with the same set of properties. Choosing sensible defaults even allows you to reduce your total codebase.

$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
}

关于powershell - 测试连接内解析 DnsName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606073/

相关文章:

c# - 通过 exe 文件运行 c# 测试项目

powershell-2.0 - 迭代来自 PSCustomObject 的键名

powershell - 隐藏 Invoke-WebRequest 的进度

powershell - 没有输出Powershell脚本

powershell - 从 Windows Server 2008 上的脚本打开 url

powershell - 重命名项目 : Cannot rename because item at . .. 不存在

PowerShell 缺少终止符 : "

powershell - 如何使用Powershell对Excel列进行排序

gridview - 脚本完成时如何防止关闭 GridView

datetime - 文件日期元数据无法正确显示