Created
September 6, 2024 12:57
-
-
Save msoler8785/25cfe7a0b9b76aa9019f8207fd2f1385 to your computer and use it in GitHub Desktop.
A function to test the download speed of a website.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires PowerShell Core