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 = "email@company.net"
$password = ConvertTo-SecureString "securepassword" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential($email, $password)
#$credentials = Get-Credential
Connect-EWSService -Mailbox $email -ServiceUrl "https://outlook.office365.com/company.net/EWS/Exchange.asmx" -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 "https://outlook.office365.com/Company.net/EWS/Exchange.asmx" -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.
Thanks