Skip to content

Instantly share code, notes, and snippets.

@msoler8785
Created September 6, 2024 12:57
Show Gist options
  • Save msoler8785/25cfe7a0b9b76aa9019f8207fd2f1385 to your computer and use it in GitHub Desktop.
Save msoler8785/25cfe7a0b9b76aa9019f8207fd2f1385 to your computer and use it in GitHub Desktop.
A function to test the download speed of a website.
function Test-Speed {
param(
[string] $TestUrl
)
# Create an HttpClient object
$client = New-Object System.Net.Http.HttpClient;
# Create a Stopwatch to test the download speed.
$sw = New-Object System.Diagnostics.Stopwatch;
# Start the Stopwatch, retrieve the URL, and then stop the Stopwatch
$sw.Start();
$response = $client.GetAsync($TestUrl).Result;
$sw.Stop();
# Calculate the speed in Mbit/s (SI Units)
$downloadSpeedMbps = ($response.Content.Headers.ContentLength * 8.0 / $sw.Elapsed.TotalSeconds) / 1000000.0;
if ($response -eq $null) {
Write-Error "An unknown error occured while testing $TestUrl";
return;
}
$result = [pscustomobject]@{
IsSuccessfull = $response.IsSuccessStatusCode
ResponseSize = $response.Content.Headers.ContentLength.ToString("0 bytes")
Status = $response.ReasonPhrase
TotalSeconds = $sw.Elapsed.TotalSeconds
TotalMilliseconds = $sw.Elapsed.TotalMilliseconds
DownloadSpeed = $downloadSpeedMbps.ToString("0 Mbps")
};
return $result;
}
@msoler8785
Copy link
Author

Requires PowerShell Core

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