Created
July 16, 2018 00:06
-
-
Save LawrenceHwang/96272b1b7a07a9fd75f47b1d95d6981c to your computer and use it in GitHub Desktop.
Invoke-BetterWebRequest - A fix for TLS 1.2 on Windows PowerShell
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 Invoke-BetterWebRequest { | |
[CmdletBinding()] | |
param( | |
# Hashtable for the Invoke-WebRequest | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] | |
[hashtable] | |
$iwrSplat | |
) | |
try { | |
Write-Verbose "Trying to obtain the $uri" -Verbose | |
Invoke-WebRequest @iwrSplat | |
} | |
catch [System.Net.WebException] { | |
Write-Verbose 'Previous attempt failed. The reason could be the TLS setting. Trying to recover using TLS1.2.' -Verbose | |
$originalSecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol | |
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 | |
Invoke-WebRequest @iwrSplat | |
} | |
catch { | |
$error[0] | Format-List * -force | |
throw | |
} | |
finally { | |
if ($originalSecurityProtocol) { | |
[System.Net.ServicePointManager]::SecurityProtocol = $originalSecurityProtocol | |
Remove-Variable -Name originalSecurityProtocol | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment