我想知道如何退回Resolve-DnsName
我的输出Test-Connection
脚本并将其添加到我创建的 CSV 中。
我喜欢从中捕获名称、类型、TTL、部分。
仅调用Resolve-DnsName
当 ping 不成功时。
$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
如果你想生成表格输出always使用同一组属性统一创建对象。选择合理的默认值甚至可以减少总代码库。
$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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)