改寫自以下的 QA,因為它似乎有點問題
https://community.spiceworks.com/topic/337701-ping-via-powershell-log-results-with-timestamp
[CmdletBinding()]
Param (
[int32]$Count = 5,
[int32]$Waittime=1,
[Parameter(ValueFromPipeline=$true)]
[String[]]$Computers = @("www.hinet.net","127.0.0.1"),
[String]$LogPath = "c:\temp\pinglog.csv"
)
#若是透過 Pipeline 進來,會每個元素執行 Process 一次
process
{
$Ping = @()
#Test if path exists, if not, create it
If (-not (Test-Path (Split-Path $LogPath) -PathType Container))
{ Write-Verbose "Folder doesn’t exist $(Split-Path $LogPath), creating…"
New-Item (Split-Path $LogPath) -ItemType Directory | Out-Null
}
#Test if log file exists, if not seed it with a header row
If (-not (Test-Path $LogPath))
{ Write-Verbose "Log file doesn’t exist: $($LogPath), creating…"
Add-Content -Value ‘"TimeStamp","Source","Destination","IPV4Address","Status","ResponseTime"’ -Path $LogPath
}
#Log collection loop
Write-Verbose "Beginning Ping monitoring of $Comptuer for $Count tries:"
for($i=0;$i -lt $Count; $i++)
{
foreach($Computer in $Computers)
{
$Ping = Get-WmiObject Win32_PingStatus -Filter "Address = ‘$Computer’" | Select @{Label="TimeStamp";Expression={Get-Date}},@{Label="Source";Expression={ $_.__Server }},@{Label="Destination";Expression={ $_.Address }},IPv4Address,@{Label="Status";Expression={ If ($_.StatusCode -ne 0) {"Failed"} Else {"Ok"}}},ResponseTime
$Result = $Ping | Select TimeStamp,Source,Destination,IPv4Address,Status,ResponseTime | ConvertTo-Csv -NoTypeInformation
$Result[1] | Add-Content -Path $LogPath
Write-verbose ($Ping | Select TimeStamp,Source,Destination,IPv4Address,Status,ResponseTime | Format-Table -AutoSize | Out-String)
}
Start-Sleep -Seconds $Waittime
}
}
執行範例如下:
.\PingTest.ps1 -LogPath "C:\temp\pingres.txt" -Computers @("www.hinet.net","127.0.0.1") -verbose