none
getting errors using EWS API to retrieve retentiontag details using impersonation RRS feed

  • Question

  • Hi there

    I am getting errors using EWS API to retrieve retentiontag details using impersonation on mailboxes in onprem or EOL. This script used to work - I wrote it last year and worked without problem but now after trying to debug it i see that $exchangeservice.GetUserRetentionPolicyTags() returns no details of tags - see output - not sure what is wrong here

    RetentionPolicyTags : {}
    Result              : Success
    ErrorCode           : NoError
    ErrorMessage        : 
    ErrorDetails        : {}
    ErrorProperties     : {}

    This is the code i am using:






    [CmdletBinding()]

        param(

        [Parameter(
        Position = 0,
        Mandatory=$true,
        ValueFromPipelineByPropertyName=$true
        
        )]
        [String[]]
        $PrimarySmtpAddress,

        [parameter( Mandatory=$false, Position=1)]
    [switch]$MultiThread=$false

        

    )




            
        begin{    
            
            $error.clear()
            [string]$LogFile = "C:\Temp\Log.txt"  
            if($LogFile)
            {
                Remove-Item $LogFile -ea SilentlyContinue
            }

         $o365credential = get-credential -credential email@domain.com
            $proxysettings = New-PSSessionOption -ProxyAccessType IEConfig
            $ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $o365credential -Authentication "Basic" -AllowRedirection -SessionOption $proxysettings
            Import-PSSession $ExchangeSession -Prefix o365 -AllowClobber
                    


            Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
            $exchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013)

           
    }



    process{
       
      
      
      function Get-MailboxFoldertags()
      {
           param(


               [Parameter(ValueFromPipelineByPropertyName=$true)]
                [string]
                $user,
            [Microsoft.Exchange.WebServices.Data.ExchangeService]$exchangeService
               
                
              

           )  
           
            $retentioninfo = @()
            $retentiontags = @()
           
               
                


                            write-host -ForegroundColor DarkBlue "DEF in function"
                            $FPageSize = 500
                            $FOffset = 0
                           
                            $folderView = new-object Microsoft.Exchange.WebServices.Data.FolderView($FPageSize,$FOffset,[Microsoft.Exchange.WebServices.Data.OffsetBasePoint]::Beginning)
                            $folderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
                            $oFindFolders = $exchangeService.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$null,$folderView)
                            #?{(($_.DisplayName -notlike 'Calendar') -and ($_.DisplayName -notlike '*contacts') -and ($_.DisplayName -notlike '*recipient*'))}
                
                            $RetentionTags = $exchangeService.GetUserRetentionPolicyTags()
                    

                                function GetTagName($tagGUID) {
                                if (!$tagGUID) { return ($RetentionTags.RetentionPolicyTags | ? {$_.Type -eq "All"}).DisplayName }
                                foreach ($tag in $RetentionTags.RetentionPolicyTags) {
                                if ($tag.RetentionId -eq $tagGUID ) { return $tag.DisplayName }
                                }
                            }


                                function GetRetentionAction($tagGUID)  {
                                if (!$tagGUID) { return ($RetentionTags.RetentionPolicyTags | ? {$_.Type -eq "All"}).RetentionAction }
                                foreach ($tag in $RetentionTags.RetentionPolicyTags) {
                                if ($tag.RetentionId -eq $tagGUID ) { return $tag.RetentionAction }

                                }
                            }

                                 function GetRetentionPeriod($tagGUID)  {
                                if (!$tagGUID) { return ($RetentionTags.RetentionPolicyTags | ? {$_.Type -eq "All"}).RetentionPeriod }
                                foreach ($tag in $RetentionTags.RetentionPolicyTags) {
                                if ($tag.RetentionId -eq $tagGUID ) { return $tag.RetentionPeriod }

                                }
                            }
                                
                           
                           
                               # $itemView = new-object Microsoft.Exchange.WebServices.Data.ItemView($FpageSize,$FOffset,[Microsoft.Exchange.WebServices.Data.OffsetBasePoint]::Beginning)
                               # $itemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Shallow
                               # $itemView.PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet(
                                #[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)
                                    $oFindFolders | %{
                                  #  $oFinditems = $exchangeService.FindItems($_.Id,$itemview)
                                        
                                    $obj = New-Object PSObject
                                    $obj | add-member noteproperty DisplayName $_.DisplayName
                                    $obj | add-member noteproperty PolicyTag (GetTagName $_.PolicyTag.RetentionId)
                                    $obj | add-member noteproperty ArchiveTag (GetTagName $_.ArchiveTag.RetentionId)                        
                                    $obj | add-member noteproperty RetentionActionPolicyTag (GetRetentionAction $_.PolicyTag.RetentionId)
                                    $obj | add-member noteproperty RetentionActionArchiveTag (GetRetentionAction $_.ArchiveTag.RetentionId)
                                    $obj | add-member noteproperty RetentionPeriodPolicyTag (GetRetentionPeriod $_.PolicyTag.RetentionId)
                                    $obj | add-member noteproperty RetentionPeriodArchiveTag (GetRetentionPeriod $_.ArchiveTag.RetentionId)
                                    $obj | add-member noteproperty Usermailbox $user
                                    $obj | add-member noteproperty FolderItemCount $_.TotalCount
                                    $retentioninfo += $obj       
                                

                                }


                                
        $retentioninfo | Export-Csv .\report.csv -NoTypeInformation
              }                                             
             foreach($user in $PrimarySmtpAddress){

             try{ 
                        write-host -ForegroundColor DarkGreen "in the trycatch"
                        $CurrentUser = get-recipient $user -ErrorAction STOP
                         
                                              
                               
                        if(($CurrentUser).recipienttype -eq 'UserMailbox')
                        {
                            $exchangeService.UseDefaultCredentials =$true
                            #$exchangeService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList $credential.UserName, $credential.GetNetworkCredential().password
                            $id = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId -ArgumentList "SmtpAddress",$user
                            $exchangeService.ImpersonatedUserId = $id

                            $exchangeService.AutodiscoverUrl($user)
                            Get-MailboxFoldertags $user $exchangeService
                                         
                        }
                         
                        
                        
                        
                        
                        else{

                        
                        $exchangeService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList $o365credential.UserName, $o365credential.GetNetworkCredential().password
                        $id = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId -ArgumentList "SmtpAddress",$user
                        $exchangeService.ImpersonatedUserId = $id
                        $exchangeService.Url = "https://outlook.office365.com/EWS/Exchange.asmx"

                        Get-MailboxFoldertags $user $exchangeService

                        }  
                
                }catch{
                            
                    $errcond = $_.Exception.Message
                    $timestamp = (get-date).DateTime
                    "Time of exception:  $timestamp" | Out-File $LogFile -Append
                    "User: $user" | out-file $LogFile -Append
                    $errcond | out-file -FilePath $LogFile -append
                }
         
        
        }

       
        


         
      
       
               
        

    Tuesday, July 16, 2019 4:04 PM

Answers

  • The first thing I would try is removing application Impersonation from the user and wait 30 minutes then grant the permission back to user wait 30 minutes then try your script. The other thing is create a temp user assign it impersonation rights and see if it works. There isn't a lot more you can do if everything is setup correctly in EOL without going through MS support.
    Thursday, July 18, 2019 10:19 PM

All replies

  • Hi Nicholas,

    Based on your description, you are getting errors using EWS API to retrieve retention tag details using impersonation. Since we mainly discuss Exchange online topics in this forum and your issue is more related to Exchange development side, to better resolve it, I will move the thread to Exchange Server Development forum.

    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. 

    Regards,

    Manu Meng


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnsf@microsoft.com.

    Wednesday, July 17, 2019 5:20 AM
  • I would first check if a retention policy has been applied to the Mailbox, a blank result would be valid if that's the case, The other thing you could do is look for the IPM.Configuration.MRM FAI item in the Inbox folder using a MAPI editor to see if the Item exists and if there maybe issue with it. 

    Cheers
    Glen

    Thursday, July 18, 2019 12:00 AM
  • Hi there - weirdly it is now working without me changing anything for onpremise mailboxes - but not for Exchange Online users - with debugging I caught the error 'Exception calling "FindFolders" with "3" argument(s): "The account does not have permission to impersonate the requested user."' - even though the EOL admin account I use with get-credential - I have assigned the ApplicationImpersonation role to it?
    Thursday, July 18, 2019 10:57 AM
  • The first thing I would try is removing application Impersonation from the user and wait 30 minutes then grant the permission back to user wait 30 minutes then try your script. The other thing is create a temp user assign it impersonation rights and see if it works. There isn't a lot more you can do if everything is setup correctly in EOL without going through MS support.
    Thursday, July 18, 2019 10:19 PM