Ignoring SSL Certificate Errors with WebClient

First off, credit where credit’s due.

The incomparable Lee Holmes first tackled this in his blog: http://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 http://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 http://poshcode.org/624, and, yes, it works in V1.

Here’s the code

 function New-TrustAllWebClient {
# found at http://poshcode.org/624
 # Create a compilation environment
 $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
 $Params=New-Object System.CodeDom.Compiler.CompilerParameters
 $Params.ReferencedAssemblies.Add(“System.DLL”) > $null
   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;

 ## We now create an instance of the TrustAll and attach it to the ServicePointManager

 ## 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.
   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;

 ## Now return the custom WebClient. It behaves almost like a normal WebClient.
 return $WebClient




Comments (0)