Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ChatGPT Multi target ping with log rotation to help isolate results during reported issues
- # second revision added a second failure only file, and console output during execution
- # Configurable variables
- $Targets = @("192.168.1.1","192.168.1.10","8.8.8.8") # Routers, switches, VM, etc
- $Frequency = 5 # seconds between samples of the SAME host
- $Persistent = $true # $true = run until stopped, $false = stop after $Duration
- $Duration = 600 # seconds total runtime (ignored if $Persistent = $true)
- # Function: get current hourly log file name
- function Get-HourlyLogFile {
- $timestamp = Get-Date -Format "yyyyMMddHH"
- $logfile = ".\pinglog_$timestamp.csv"
- if (-not (Test-Path $logfile)) {
- "Timestamp,Target,Status,Latency_ms" | Out-File -FilePath $logfile -Encoding utf8
- }
- return $logfile
- }
- # Function: get current daily packet loss log file name
- function Get-DailyLossLog {
- $timestamp = Get-Date -Format "yyyyMMdd"
- $lossfile = ".\packetloss_$timestamp.csv"
- if (-not (Test-Path $lossfile)) {
- "Timestamp,Target" | Out-File -FilePath $lossfile -Encoding utf8
- }
- return $lossfile
- }
- # Function: run one ping attempt
- function Test-Target ($target) {
- $result = Test-Connection -ComputerName $target -Count 1 -ErrorAction SilentlyContinue
- $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
- if ($null -ne $result) {
- $latency = "{0:N2}" -f $result.ResponseTime
- $data = [PSCustomObject]@{
- Timestamp = $timestamp
- Target = $target
- Status = "Success"
- Latency_ms = $latency
- }
- }
- else {
- $data = [PSCustomObject]@{
- Timestamp = $timestamp
- Target = $target
- Status = "Timeout"
- Latency_ms = ""
- }
- # Also log timeout to packet loss log
- $losslog = Get-DailyLossLog
- "$timestamp,$target" | Out-File -FilePath $losslog -Append -Encoding utf8
- }
- # Console output
- Write-Host ("{0} | {1,-15} | {2,-7} | {3}" -f $data.Timestamp,$data.Target,$data.Status,$data.Latency_ms)
- return $data
- }
- # Main loop
- $start = Get-Date
- $index = 0
- while ($true) {
- $target = $Targets[$index % $Targets.Count]
- $data = Test-Target $target
- $log = Get-HourlyLogFile
- $data | Export-Csv -Path $log -Append -NoTypeInformation
- Start-Sleep -Seconds $Frequency
- if (-not $Persistent) {
- $elapsed = (New-TimeSpan -Start $start -End (Get-Date)).TotalSeconds
- if ($elapsed -ge $Duration) { break }
- }
- $index++
- }
Advertisement