Skip to content

Instantly share code, notes, and snippets.

@LawrenceHwang
Created July 16, 2018 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LawrenceHwang/96272b1b7a07a9fd75f47b1d95d6981c to your computer and use it in GitHub Desktop.
Save LawrenceHwang/96272b1b7a07a9fd75f47b1d95d6981c to your computer and use it in GitHub Desktop.
Invoke-BetterWebRequest - A fix for TLS 1.2 on Windows PowerShell
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