我想知道如何从Resolve-DnsName
脚本返回Test-Connection
输出并将其添加到我创建的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中没有添加任何新内容。
答案 0 :(得分:2)
你遇到了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
如果要生成表格输出始终使用相同的属性集统一创建对象。选择合理的默认值甚至可以减少总代码库。
$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
}