none
Error bind to folder with EWS API 1.2 on 2008R2 server RRS feed

  • Question

  • I've a script which works fine under Windows 7 but not under Windows 2008R2. When the script runs on 2008R2 and tries to bind to a folder the following error is generated:

    Exception calling "Bind" with "2" argument(s): "The request failed. De onderliggende verbinding is gesloten: Bi
    j verzending is een onverwachte fout opgetreden."
    At C:\Temp\MoveMailItems.ps1:39 char:61
    +     $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind <<<< ($service,$folderid)
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

    The part of the script where it fails:
    #Bind to Inbox source   
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)    
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

    When generating the full error the following is viible:
    Exception             : System.Management.Automation.MethodInvocationException: Exception calling "Bind" with "
                            2" argument(s): "The request failed. De onderliggende verbinding is gesloten: Bij verze
                            nding is een onverwachte fout opgetreden." ---> Microsoft.Exchange.WebServices.Data.Ser
                            viceRequestException: The request failed. De onderliggende verbinding is gesloten: Bij 
                            verzending is een onverwachte fout opgetreden. ---> System.Net.WebException: De onderli
                            ggende verbinding is gesloten: Bij verzending is een onverwachte fout opgetreden. ---> 
                            System.Management.Automation.PSInvalidOperationException: There is no Runspace availabl
                            e to run scripts in this thread. You can provide one in the DefaultRunspace property of
                             the System.Management.Automation.Runspaces.Runspace type. The script block you attempt
                            ed to invoke was: $true

    What do I need to do to make it work on 2008R2?

    Wednesday, July 18, 2012 4:42 PM

Answers

  • There is problem with running Delegates in the version 1.2 of the Managed API see http://social.technet.microsoft.com/Forums/en-AU/exchangesvrdevelopment/thread/ad493b72-6465-450b-bd49-8f15675d7f53 so get rid of

    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
     [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}  
    

    and replace with

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

    Make sure you close any existing powershell sessions where you may have run the old script and start a new PS session before testing.

    Cheers
    Glen

    • Marked as answer by Remco Tiel Thursday, July 19, 2012 5:18 PM
    Wednesday, July 18, 2012 11:31 PM

All replies

  • This is the script:    
    ## check where the API is installed
    	If (Test-Path -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"){
    		Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"}
    	Else{
    		Add-Type -Path "E:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"}
    	
      
    	$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
        $user = [ADSI]"LDAP://<SID=$sid>"
        $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList ([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)
        $service.AutodiscoverUrl($user.Properties.mail)
    
        if($Impersonate) {
            $ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId -ArgumentList ([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress),$Impersonate
            $service.ImpersonatedUserId = $ImpersonatedUserId
        }
    
    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
     [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}  
    
    #$AQSString = "System.Message.AttachmentContents:*.pdf"
    #"System.Size:5mb..10mb"
    #"System.Message.FromAddress:(fred@onmicrosoft.com OR amanda@onmicrosoft.com)" 
    #"System.Subject:FootBall"
    $AQSString = "System.Message.FromAddress:(Bespreekbureau)"
    $DestinationName = "test@chasse.nl"
    
    Get-Mailbox rtiel | ForEach-Object{ 
    	$MailboxName = $_.PrimarySMTPAddress.ToString()
    	$AccountName = $_.SamAccountName.ToString()
    	$rptCollection = @()
    	$folderid = ""
    	$Inbox = ""
    	
    	"Processing Mailbox : " + $MailboxName
    	
    	#Bind to Inbox source   
    	$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
    	$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    	Start-Sleep -Seconds 1
    	$error[0] | fl -force 
    	
    	 #Bind to SentItems source   
    	$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)     
    	$SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    	Start-Sleep -Seconds 1
    	$Error[0] | fl -Force
    	
    	 #Bind to SentItems destination
    	$Destfolderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$DestinationName)     
    	$DestSentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$Destfolderid)
    	Start-Sleep -Seconds 1
    	
    	#Define ItemView to retrieve just 1000 Items    
    	$ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
    	$fiItems = $null    
    	do{    
    	    $fiItems = $service.FindItems($SentItems.Id,$AQSString,$ivItemView)    
    	    #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)
    	    [INT]$Rcount = 0
    		foreach($Item in $fiItems.Items){      
    	        #$Item.Move($DestSentItems.Id)
    			$Rcount++
    			$rptCollection += $Item.Subject + "," + $Item.DisplayTo
    	    }    
    	    $Rcount.ToString() + " Items moved successfully"
    		$ivItemView.Offset += $fiItems.Items.Count    
    	}while($fiItems.MoreAvailable -eq $true)
    
    	$FileLocation = "C:\"
    	$FileName = Get-Date –f "dd-MM-yyyy HH-mm-ss"
    
    	$rptCollection
    	#$rptCollection | Out-File "$FileLocation $FileName $AccountName.csv"
    }

    Wednesday, July 18, 2012 4:43 PM
  • There is problem with running Delegates in the version 1.2 of the Managed API see http://social.technet.microsoft.com/Forums/en-AU/exchangesvrdevelopment/thread/ad493b72-6465-450b-bd49-8f15675d7f53 so get rid of

    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
     [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}  
    

    and replace with

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

    Make sure you close any existing powershell sessions where you may have run the old script and start a new PS session before testing.

    Cheers
    Glen

    • Marked as answer by Remco Tiel Thursday, July 19, 2012 5:18 PM
    Wednesday, July 18, 2012 11:31 PM
  • Thnx Glen!!! This solved my problem...

    Remco

    Thursday, July 19, 2012 5:18 PM