EWS service bind failure with powershell

Stefano Colombo 221 Reputation points
2024-06-25T06:59:24.2+00:00

I'm facing an issue while trying to use a powershell script to connecto to Exchange 2016 EWS service to extract calendar info from users' mailboxes.

The error I get is

Exception calling "Bind" with "2" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized."

At D:\Scripts\CalendarDumpToCSV\CalendarDumpToCSV-prova.ps1:141 char:1

  • $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($servi ...
  • 
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    
        + FullyQualifiedErrorId : ServiceRequestException
    
    

The relevant part of the script is

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)

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

The user that is used to make the bind is the exchange Org Admin and has also been granted impersonation rights with

New-ManagementRoleAssignment -name:impersonationAssignmen -Role:ApplicationImpersonation -User:exchadmin@xxx.xx

Exchange Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,450 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,256 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Vasil Michev 98,946 Reputation points MVP
    2024-06-25T08:00:48.7966667+00:00

    You need to impersonate the owner of the folder before attempting the Bind operation. Something like this should do:

    $smtpAddress = "user@domain.com"
    
    $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $smtpAddress)
    

  2. Stefano Colombo 221 Reputation points
    2024-06-25T12:39:09.91+00:00

    I followed another thread's solution and installed the scripts into another server from the exchange server itself and worked without impersonation.

    0 comments No comments