Microsoft - Exchange - PowerShell - EWS - Notes

Connect to an EWS that is using (self-signed) SSL

Using:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {return $true}

Gives the error:

Exception calling "Bind" with "2" argument(s): "The request failed. The underlying connection was closed: An unexpected error occurred on a send."

At C:\Scripts\Create-Folders.ps1:18 char:1

+ $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : ServiceRequestException

Solution: use the following code instead of ServerCertificateValidationCallback:

## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
 
## Code From http://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") | Out-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
 
## end code from http://poshcode.org/624

Microsoft Developer Network - Forum - EWS Api problem connecting Inbox