Skip to content

Instantly share code, notes, and snippets.

@Kayli
Created September 8, 2017 19:14
Show Gist options
  • Save Kayli/8bef65f6addaa789bda03e910bb2caa9 to your computer and use it in GitHub Desktop.
Save Kayli/8bef65f6addaa789bda03e910bb2caa9 to your computer and use it in GitHub Desktop.
PowerShell script to ping a Url with retries and timeouts
param
(
[string] $Url,
[int] $MaxRetries = 3,
[int] $OneRetryTimeout = 5,
[int] $OverallTimeout = 60,
[int] $WaitBetweenRetries = 1
)
if ([System.String]::IsNullOrWhiteSpace($Url))
{
throw "Parameter 'Url' cannot be empty"
}
$Success = $false
$RetriesLeft = $MaxRetries
$TimeLeft = [timespan]::fromseconds($OverallTimeout)
do
{
Write-Host "Pinging url - $Url"
$StopWatch = [Diagnostics.Stopwatch]::StartNew()
try
{
$Response = Invoke-WebRequest $Url -UseBasicParsing -TimeoutSec $OneRetryTimeout
$StatusCode = $Response.StatusDescription
$StatusCodeInt = $Response.StatusCode
$StatusText = "Ping returned status $StatusCode ($StatusCodeInt)"
$ExceptionOccurred = $false
}
catch
{
if ($_.Exception.Response.StatusCode)
{
$StatusCode = $_.Exception.Response.StatusCode
$StatusCodeInt = $StatusCode.value__
$StatusText = "Ping returned status $StatusCode ($StatusCodeInt)"
}
else
{
$StatusText = $_.Exception.Message
}
$ExceptionOccurred = $true
}
$StopWatch.Stop()
Write-Host $StatusText
Write-Host 'Time elapsed' $StopWatch.Elapsed
$TimeLeft-=$StopWatch.Elapsed
$Success = (($StatusCodeInt -eq 200) -and -not($ExceptionOccurred))
$RetriesLeft--
Start-Sleep $WaitBetweenRetries
$TimeLeft-=[timespan]::fromseconds($WaitBetweenRetries)
}
while (($Success -eq $false) -and ($RetriesLeft -ge 0) -and ($TimeLeft -ge 0))
if ($Success)
{
Write-Host "Ping OK!" -ForegroundColor Green
}
else
{
throw "Ping failed: '$Url'"
}
@birkhall
Copy link

Is there a way to use this with an IP address instead of a URL?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment