当服务器被 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
Run Code Online (Sandbox Code Playgroud)
当前脚本:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为您的错误源于$pingdaddress = (Test-Connection -ComputerName $thisservername -Count 1 -ErrorAction SilentlyContinue -Verbose).IPV4Address.IPAddressToString
. 如果无法解析服务器名称,则返回的连接对象(Win32_PingStatus 对象)Test-Connection
将为$null
. 然后,您尝试访问 null 对象上的属性,这是不允许的。
我会将“成功”部分拆分为它自己的列。您可以通过向 CSV 添加另一列来实现此目的,例如: NameMatch
or 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
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您想稍后生成报告,您可以执行以下操作:
$problemServers = Import-Csv -Path c:\example.csv | ? NameMatch -eq $false
Run Code Online (Sandbox Code Playgroud)
示例.csv:
Name,IPAddress,NameMatch
server1,10.0.0.1,"True"
server2,10.0.0.2,
server3,10.0.0.3,"False"
Run Code Online (Sandbox Code Playgroud)
首次运行脚本时,NameMatch 列可以为空(就像 server2 一样),脚本将填充它。
归档时间: |
|
查看次数: |
811 次 |
最近记录: |