Untitled

 avatar
unknown
plain_text
a month ago
5.0 kB
23
Indexable
# Path to log file
$LogFile = "network_monitor.log"

# Running averages
$global:AvgPingBBC = $null
$global:AvgPingRouter = $null
$global:PingCountBBC = 0
$global:PingCountRouter = 0

function Update-Average {
    param([ref]$CurrentAvg, [ref]$Count, [double]$NewValue)
    if ($null -eq $CurrentAvg.Value) {
        $CurrentAvg.Value = $NewValue
        $Count.Value = 1
    } else {
        $Count.Value++
        $CurrentAvg.Value = (($CurrentAvg.Value * ($Count.Value - 1)) + $NewValue) / $Count.Value
    }
}

function Get-Color {
    param(
        [bool]$StatusOk,
        [double]$Ping,
        [double]$AvgPing,
        [int]$LossPercent
    )

    if (-not $StatusOk) { return "Red" }
    if ($LossPercent -ge 50) { return "Red" }
    if ($Ping -gt ($AvgPing * 1.5)) { return "Red" }
    if ($LossPercent -gt 0) { return "Yellow" }
    if ($Ping -gt $AvgPing) { return "Yellow" }
    return "Green"
}

Write-Host "Monitoring started... press Ctrl+C to stop."

while ($true) {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $jobs = @()

    $jobs += Start-Job -ScriptBlock {
        try {
            Resolve-DnsName -Name "bbc.co.uk" -Server "192.168.1.254" -ErrorAction Stop | Out-Null
            $true
        } catch { $false }
    }
    $jobs += Start-Job -ScriptBlock {
        try {
            Resolve-DnsName -Name "bbc.co.uk" -Server "1.1.1.1" -ErrorAction Stop | Out-Null
            $true
        } catch { $false }
    }
    $jobs += Start-Job -ScriptBlock {
        $count = 4
        $ping = Test-Connection -ComputerName "bbc.co.uk" -Count $count -ErrorAction SilentlyContinue
        if ($ping) {
            $avg = [math]::Round(($ping | Measure-Object -Property ResponseTime -Average).Average, 2)
            $loss = [math]::Round((($count - $ping.Count) / $count) * 100, 0)
            @{ Avg = $avg; Loss = $loss }
        } else { @{ Avg = $null; Loss = 100 } }
    }
    $jobs += Start-Job -ScriptBlock {
        $count = 4
        $ping = Test-Connection -ComputerName "192.168.1.254" -Count $count -ErrorAction SilentlyContinue
        if ($ping) {
            $avg = [math]::Round(($ping | Measure-Object -Property ResponseTime -Average).Average, 2)
            $loss = [math]::Round((($count - $ping.Count) / $count) * 100, 0)
            @{ Avg = $avg; Loss = $loss }
        } else { @{ Avg = $null; Loss = 100 } }
    }

    Wait-Job $jobs | Out-Null

    $results = foreach ($job in $jobs) {
        try { Receive-Job $job -ErrorAction Stop } catch { $null } finally { Remove-Job $job -Force }
    }

    $dns1Ok     = $results[0]
    $dns2Ok     = $results[1]
    $pingBBC    = $results[2]
    $pingRouter = $results[3]

    if ($pingBBC.Avg -ne $null)    { Update-Average ([ref]$global:AvgPingBBC) ([ref]$global:PingCountBBC) $pingBBC.Avg }
    if ($pingRouter.Avg -ne $null) { Update-Average ([ref]$global:AvgPingRouter) ([ref]$global:PingCountRouter) $pingRouter.Avg }

    # Determine colors
    $colorDns1 = if ($dns1Ok) { "Green" } else { "Red" }
    $colorDns2 = if ($dns2Ok) { "Green" } else { "Red" }
    $colorPingBBC = Get-Color -StatusOk $dns1Ok -Ping $pingBBC.Avg -AvgPing $global:AvgPingBBC -LossPercent $pingBBC.Loss
    $colorPingRouter = Get-Color -StatusOk $dns2Ok -Ping $pingRouter.Avg -AvgPing $global:AvgPingRouter -LossPercent $pingRouter.Loss

    # Compose output strings
    $consoleOutput = @(
        "$timestamp | DNS(192.168.1.254)=",
        $dns1Ok,
        " | DNS(1.1.1.1)=",
        $dns2Ok,
        " | PingBBC=",
        "$($pingBBC.Avg) ms (loss=$($pingBBC.Loss)%, avg=$([math]::Round($global:AvgPingBBC,2)) ms)",
        " | PingRouter=",
        "$($pingRouter.Avg) ms (loss=$($pingRouter.Loss)%, avg=$([math]::Round($global:AvgPingRouter,2)) ms)"
    )

    # Print colored console output
    Write-Host $consoleOutput[0] -NoNewline
    Write-Host $consoleOutput[1] -ForegroundColor $colorDns1 -NoNewline
    Write-Host $consoleOutput[2] -NoNewline
    Write-Host $consoleOutput[3] -ForegroundColor $colorDns2 -NoNewline
    Write-Host $consoleOutput[4] -NoNewline
    Write-Host $consoleOutput[5] -ForegroundColor $colorPingBBC -NoNewline
    Write-Host $consoleOutput[6] -NoNewline
    Write-Host $consoleOutput[7] -ForegroundColor $colorPingRouter

    # Decide if logging is needed: any failure or above-average ping/loss?
    $logCondition = -not $dns1Ok -or -not $dns2Ok `
        -or ($colorPingBBC -ne "Green") `
        -or ($colorPingRouter -ne "Green")

    if ($logCondition) {
        $line = "$timestamp | DNS(192.168.1.254)=$dns1Ok | DNS(1.1.1.1)=$dns2Ok | " +
                "PingBBC=$($pingBBC.Avg) ms (loss=$($pingBBC.Loss)%, avg=$([math]::Round($global:AvgPingBBC,2)) ms) | " +
                "PingRouter=$($pingRouter.Avg) ms (loss=$($pingRouter.Loss)%, avg=$([math]::Round($global:AvgPingRouter,2)) ms)"
        Add-Content -Path $LogFile -Value $line
    }

    Start-Sleep -Seconds 15
}
Editor is loading...
Leave a Comment