Ignoring SSL Certificate Errors with WebClient
First off, credit where credit's due.
The incomparable Lee Holmes first tackled this in his blog: https://www.leeholmes.com/blog/2007/03/19/converting-c-to-powershell/
But I couldn't get it to work.
Then I found Bhargav Shukla's method https://blogs.technet.com/b/bshukla/archive/2010/04/12/ignoring-ssl-trust-in-powershell-system-net-webclient.aspx
It looked much the same as Lee's, but I was able to get it to work, on V2 onlyl. However, some boxes were V1-only (have to keep them on-parity with production), and I needed something that worked in V1.
Then I found Carter Shanklin's way, which doesn't just utlize arcane .NET objects, it creates the necessary assemblies on-the-fly. It's found at https://poshcode.org/624, and, yes, it works in V1.
Here's the code
function New-TrustAllWebClient {
# found at https://poshcode.org/624
# Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
<$TASource=@'>
namespace Local.ToolkitExtensions.Net.CertificatePolicy {
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
## The ESX Upload requires the Preauthenticate value to be true which is not the default
## for the System.Net.WebClient class which has very simple-to-use downloadFile and uploadfile
## methods. We create an override class which simply sets that Preauthenticate value.
## After creating an instance of the Local.ToolkitExtensions.Net.WebClient class, we use it just
## like the standard WebClient class.
$WCSource=@'
namespace Local.ToolkitExtensions.Net {
class WebClient : System.Net.WebClient {
protected override System.Net.WebRequest GetWebRequest(System.Uri uri) {
System.Net.WebRequest webRequest = base.GetWebRequest(uri);
webRequest.PreAuthenticate = true;
webRequest.Timeout = 10000;
return webRequest;
}
}
}
'@
$WCResults=$Provider.CompileAssemblyFromSource($Params,$WCSource)
$WCAssembly=$WCResults.CompiledAssembly
## Now return the custom WebClient. It behaves almost like a normal WebClient.
$WebClient=$WCAssembly.CreateInstance("Local.ToolkitExtensions.Net.WebClient")
return $WebClient
}