Get attachment from emails in O365 to a folder then delete the message

Hello all.
I am beating my head on this one and could use some help.
For some background I am work on some powershell automation with ServiceNow. My approach is to have SN send an email to a O365 email account with a JSON attached. I want to use PS to connect to that mailbox. the the attachment and save it to a folder then delete the message from O365.
this script is the closest I have come to something that works

# Import the EWS module
#Import-Module ExchangeWebServices
Import-Module EWS

# Define the Office 365 email account credentials
$email = ""
$password = ConvertTo-SecureString "securepassword" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential($email, $password)
#$credentials = Get-Credential

Connect-EWSService -Mailbox $email -ServiceUrl "" -Credential $credentials
# Define the folder path to save the attachments
$folderPath = "C:\Scripts\JSON\LandingZone\"

# Connect to the Office 365 email account
$ews = Connect-EWSService -Mailbox $email -ServiceUrl "" -Credential $credentials

# Search for emails with specific subject
#$searchResults = Search-Mailbox -Session $ews -TargetMailbox $email -SearchQuery 'subject:"TEST *"'
$searchResults = Get-EWSItem -Name Inbox #-Filter subject:TEST

# Loop through each email found
foreach ($email in $searchResults.Items) {
    # Loop through each attachment in the email
    foreach ($attachment in $email.Attachments) {
        # Save the attachment to the specified folder
        $attachment.SaveAsFile($folderPath + $attachment.Name)
    #Delete the email
    Remove-MailboxItem -Session $ews -Item $email -PermanentlyDelete

But I am getting an error

Exception calling "Bind" with "2" argument(s): "The request failed. The remote server returned an error: (404) Not Found."
At line:53 char:9
+         $folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind(
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException
You cannot call a method on a null-valued expression.
At line:67 char:17
+                 $list = $Folder.FindItems($view)
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

I would really love some help here.


Just giving this a bump.
If there is anyone out there who can assist me on this I would be very grateful!!

Without having any experience with O365 … the error messages seem to come from other code than you share. The code you shared does not have a line 53 or 67 and it does not have the code the error message complains about. :thinking: :man_shrugging:t4:

That is something I have not figured out as there are not a line 53 or 67.
Hence my confusion.

I’d recommend to start to learn how to debug your own code.

The error messages comes from the module “EWS” from the cmdlet Get-EWSItem. Your call

seems to be incomplete or wrong.

No way for me to test BTW

To get more error detail, you could set $ErrorActionPreference = Stop, then wrap your code in a try/catch block, and in the catch block, try this:

$errInfo = [PSCustomObject][Ordered] @{
	'Error Message' = $error[0].Exception.Message
	'Error Command' = $error.InvocationInfo[0].Line.Trim()
	'Command Name' 	= $error.InvocationInfo[0].InvocationName
	'Line Number' 	= $error.InvocationInfo[0].PositionMessage.Split("`r`n")[0]

If you are using PS Core, you could simply use Get-Error which provides pretty much the same info as the $error object, but in one command.

1 Like