Welcome to ciysys blog

Failed to download from Internet

Published on: 12th May 2020

Updated on: 16th Jan 2022


The following code is downloading a text file from a web server. It looks simple and straightforward.

$u2 = "https://my-test-web.com/my-file.txt"
$f2 = "my-file.txt"
Invoke-WebRequest -Uri $u2 -OutFile $f2

But, we never expect downloads to fail except for when the case of Internet connection has broken down.

If you look at the value of $u2, you might notice that it is calling HTTPS which requires Powershell to validate the SSL certificate. So, there is a chance for the above code to fail when the web server disabled Tls v1.1 and below.

To resolve and avoid the download failure, you must change the environment setting first before calling Invoke-WebRequest.

# enforce Tls1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$u2 = "https://my-test-web.com/my-file.txt"
$f2 = "my-file.txt"
Invoke-WebRequest -Uri $u2 -OutFile $f2

That's it.

Jump to #POWERSHELL blog


Lau Hon Wan, software developer.