我是PS脚本的新手。我需要帮助我的代码。 目的:从.txt文件中ping IP列表,并以csv格式输出结果。这是我到目前为止的代码。
$Iplist = Get-Content ips.txt
$group = $()
foreach ($ip in $Iplist)
{
$status = @{ "ServerIP Name" = $ip; "TimeStamp" = (Get-Date -f s) }
if (Test-Connection $ip -Count 4 -ea 0 | measure-Object -Property ResponseTime -Average)
{
$status["Results"] = "Up"
}
else
{
$status["Results"] = "Down"
}
New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
$group += $serverStatus
}
$group | export-csv c:\ping\results.csv -NoTypeInformation
答案 0 :(得分:2)
Test-Connection
会返回Win32_PingStatus
个对象。
要在PowerShell中查看此对象的其他可用内容:
$ping = Test-Connection www.google.com #or insert favorite url here
$ping | Format-List | Out-String
Test-Connection
并不只是返回一个布尔。您真的很接近,但您必须指定返回值才能计算成功的平均值:
$Iplist = Get-Content ips.txt
$group = @()
foreach ($ip in $Iplist) {
$status = @{ "ServerIP Name" = $ip; "TimeStamp" = (Get-Date -f s) }
$pings = Test-Connection $ip -Count 4 -ea 0
if ($pings) {
$status["AverageResponseTime"] =
($pings | Measure-Object -Property ResponseTime -Average).Average
$status["Results"] = "Up"
}
else {
$status["Results"] = "Down"
}
New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
$group += $serverStatus
}
$group | Export-Csv c:\ping\results.csv -NoTypeInformation