Skip to content

Instantly share code, notes, and snippets.

@danclien
Last active October 17, 2023 14:40
Show Gist options
  • Save danclien/560ad23289aa12c387fb7bae3d5e9478 to your computer and use it in GitHub Desktop.
Save danclien/560ad23289aa12c387fb7bae3d5e9478 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Check internet connection by pinging a list of remote and local servers
#>
# Local gateway recommended
$localServers = @("192.168.1.1")
# Remote servers to ping
$remoteServers = @(
"8.8.8.8",
"9.9.9.9",
"4.2.2.2"
)
$pingIntervalSeconds = 1
$pingTimeoutSeconds = 1
$outputFile = "check-internet-$(Get-Date -Format 'yyyy-MM-dd-HHmm').log"
$outputPath = Join-Path (Get-Location) $outputFile
function Ping-Servers()
{
<#
.SYNOPSIS
Ping all servers and return $true if any pings are successful
#>
param (
# Array of servers to ping
[Parameter(
Mandatory = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0
)]
$Servers
)
$result = $Servers | ForEach-Object {
return Test-Connection -TargetName $_ -IPv4 -Quiet -Count 1 -TimeoutSeconds $pingTimeoutSeconds
}
return ($result -Contains $true)
}
Write-Host ""
Write-Host "Log output: $outputPath"
Write-Host ""
Write-Output "Starting ping tests for" | Tee-Object -FilePath $outputPath
Write-Output " Remote servers: $remoteServers" | Tee-Object -FilePath $outputPath -Append
Write-Output " Local servers: $localServers" | Tee-Object -FilePath $outputPath -Append
Write-Output "" | Tee-Object -FilePath $outputPath -Append
$failing = $false
$failingStartTime = $null
while ($true) {
$remoteResult = Ping-Servers -Servers $remoteServers
$localResult = Ping-Servers -Servers $localServers
if($remoteResult -and (-not $failing)) {
# Success: Successful remote ping and not currently failing, do nothing
} elseif((-not $remoteResult) -and (-not $failing)) {
# Failure starting: Failed remote pings and not currently failing
$failing = $true
$failingStartTime = Get-Date
Write-Output "$($failingStartTime): Failed to ping all remote servers, local ping result: $localResult" | Tee-Object -FilePath $outputPath -Append
} elseif((-not $remoteResult) -and $failing) {
# Failure continuing: Failed remote pings and currently failing, do nothing
} elseif($remoteResult -and $failing) {
# Failure ending: Successful remote ping and currently failing
$failing = $false
$failingEndTime = Get-Date
$duration = $failingEndTime - $failingStartTime
Write-Output "$($failingEndTime): Successfully pinged a remote servers, failure duration: $duration, local ping result: $localResult" | Tee-Object -FilePath $outputPath -Append
}
Start-Sleep -Seconds $pingIntervalSeconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment