Enabling TLS1.2 in PowerShell and Getting Ready for Windows Terminal

The Problem:

Sometimes PowerShell ISE returns the following TLS-triggered error when one implements Invoke-WebRequest or Invoke-RestMethod during a session:

“The underlying connection was closed: An unexpected error occurred on a receive…” (https://stackoverflow.com/questions/66050990/the-underlying-connection-was-closed-an-unexpected-error-occurred-on-a-receive).

The Solution:

To avoid said error, enable TLS (Transport Layer Security, https://docs.microsoft.com/en-us/microsoft-365/compliance/prepare-tls-1.2-in-office-365?view=o365-worldwide) by adding the following line before using Invoke-WebRequest (or Invoke-RestMethod):

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

For instance, to retrive URIs from mit.edu, use

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
(Invoke-WebRequest -Uri ‘mit.edu’).links.href

Similarly, to retrieve URIs from Google search results for the [corona virus] query, use

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
(Invoke-WebRequest -Uri ‘google.com/search?q=corona virus’).links.href

You may need to filter Google results with a cmdlet. Optionally, use the tool at http://www.minerazzi.com/tools/url-cleaner/muc.php to filter these.

The fix mentioned above goes away if you close the PowerShell session so as a workaround, add the fix as a PowerShell profile (https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/how-to-use-profiles-in-windows-powershell-ise?view=powershell-7.2).

A profile is a Windows PowerShell ISE script that runs automatically when you start a new session. A profile affects every Windows PowerShell ISE session that you start.

Read more about profiles in PowerShell here –> https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/how-to-use-profiles-in-windows-powershell-ise?view=powershell-7.2

Bye bye, Command Prompt. Hello, Windows Terminal:

Now on the news on Windows Terminal. The days of Command Prompt seem to be over:

Hello, Windows Terminal.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s