none
EWS via PowerShell - 401 Unauthorized

    Question

  • I'm trying perform some tasks using the EWS Managed API via Windows PowerShell, but I cannot seem to get connected.  I keep getting 401 Unauthorized responses. Any comments on what is wrong with the below? I've checked the user is enable to EWS and I'm able to connect using EWSEditor and the same credentials. Thanks for any help!

    Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
    $Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials("username@domain.com","password")
    $exchService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
    $exchService.Credentials = $Credentials
    $exchService.URL = New-Object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
    $exchService.TraceEnabled = $True
    $mailbox = "username@domain.com"
    $mbx = New-Object Microsoft.Exchange.WebServices.Data.Mailbox($mailbox)
    $folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot, $mbx )
    $MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($exchService, $folderId)

    Sunday, April 12, 2015 8:42 AM

Answers

  • Managed to fix it. Something to do with the setup of the credentials. I guess Office 365 doesn't like basic authentication.

    I've changed it to the following:

    Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
    $cred = Get-Credential
    
    $exchService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
    $exchService.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $cred.UserName, $cred.Password, $cred.Domain
    $exchService.URL = New-Object Uri("https://outlook.office365.com/EWS/Exchange.asmx")
    $exchService.TraceEnabled = $True
    $mailbox = "username@domain.com"
    $mbx = New-Object Microsoft.Exchange.WebServices.Data.Mailbox($mailbox)
    $folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot, $mbx )
    $MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($exchService, $folderId)
    

    Sunday, April 12, 2015 11:14 AM