当对服务器进行 ping 操作时,会将结果地址与库存进行比较,以保证库存保持最新。
我试图在下一个相应的单元格中将结果标记为“好”或“坏”。这种方法有点管用,只是按照我设置的工作流程,结果总是“坏”。
CSV 包含从 Excel 清单中提取的服务器名称和 IP 地址,格式如下:
name,ipaddress
server1,10.1.24.51
server2,10.1.24.52
server3,10.1.24.53
server4,10.1.27.101
server5,10.1.27.102 <--- purposely wrong IP address for testing
当前脚本:
$serverlist = Import-Csv -Path file.csv
ForEach ($server in $serverlist) {
$thisservername = $server.name
$thisserveripaddress = $server.ipaddress
$pingdaddress = (Test-Connection -ComputerName $thisservername -Count 1 -ErrorAction SilentlyContinue -Verbose).IPV4Address.IPAddressToString
if ($pingdaddress -ne $thisserveripaddress) {
#$thisservername + " bad"
$serverlist | Select-Object name,ipaddress, @{Name='connection';Expression={'bad'}} | `
Export-Csv -Path file.csv -NoTypeInformation
} else {
#$thisservername + " good"
$serverlist | Select-Object name,ipaddress, @{Name='connection';Expression={'good'}} | `
Export-Csv -Path file.csv -NoTypeInformation
}
}
答案1
我认为您的错误源于$pingdaddress = (Test-Connection -ComputerName $thisservername -Count 1 -ErrorAction SilentlyContinue -Verbose).IPV4Address.IPAddressToString
。如果无法解析服务器名称,则返回的连接对象(即 Win32_PingStatus 对象)Test-Connection
将为$null
。然后您尝试访问空对象的属性,这是不允许的。
我会将“成功”部分拆分成它自己的列。您可以通过在 CSV 中添加另一列来实现这一点,例如:NameMatch
或IPMatch
,无论哪种方式对您来说更有意义。这样,您就可以在循环中将其作为属性访问$server.NameMatch
,并在稍后对数据进行过滤/排序。
function Test-ServerNameMapping
{
[cmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_})]
[String]
$Path
)
$serverList = Import-Csv -Path $Path
foreach ($server in $serverList)
{
Write-Verbose "Testing: $($server.Name), $($server.IPAddress)"
$connectionObject = (Test-Connection -ComputerName $server.Name -Count 1 -ErrorAction SilentlyContinue)
if (-not $connectionObject)
{
Write-Verbose "Failed to resolve $($server.Name) to an IP address."
$server.namematch = $false
}
else
{
$resolvedAddress = $connectionObject.IPV4Address.ToString()
Write-Verbose "Resolved $($server.Name) to $resolvedAddress"
if ($resolvedAddress -eq $server.IPAddress)
{
Write-Verbose "$($server.IPAddress) matches found address of $resolvedAddress"
$server.namematch = $true
}
else
{
Write-Verbose "$($server.IPAddress) does not equal found address of $resolvedAddress"
$server.namematch = $false
}
}
}
$serverList | Export-Csv -Path $Path -NoTypeInformation -Force
}
然后,如果您稍后想要生成报告,您可以执行以下操作:
$problemServers = Import-Csv -Path c:\example.csv | ? NameMatch -eq $false
示例.csv:
Name,IPAddress,NameMatch
server1,10.0.0.1,"True"
server2,10.0.0.2,
server3,10.0.0.3,"False"
第一次运行脚本时,NameMatch 列可以为空(就像 server2 一样),脚本将填充它。