GithubHelp home page GithubHelp logo

david-barrett-ms / powershell-ews-scripts Goto Github PK

View Code? Open in Web Editor NEW
115.0 115.0 12.0 2.2 MB

A collection of PowerShell scripts that use EWS to perform actions against Exchange mailboxes

License: MIT License

PowerShell 100.00%

powershell-ews-scripts's People

Contributors

david-barrett-ms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

powershell-ews-scripts's Issues

Merge Mailbox Folders running as a Job

So 1.2.9 fixes the cert issue, however, it will no longer run as a background job (Start-Job)
My feeling is to do with the way it's getting the token, or the path to the MSAL DLL isn't being accounted for.

If I run my script alone, then it accepts my username/password, runs in foreground and completes
If I run my script in batch job mode, it creates the job, accepts username/password, but then throws up an instance of IE (or chrome maybe), and does a modern auth style prompt for username/password again. The job then shows as Blocked and doesn't run.

I tried hard coding the msal location path in, but didn't seem to make any difference.
When I am creating the job I am passing the correct path into the scriptblock and setting the location using that, but still no go.

Exception setting "TraceListener": "Cannot convert the "EWSTracer" value of type "EWSTracer" to type "Microsoft.Exchange.WebServices.Data.ITraceListener"."

Hi David,
I have tried to use your Merge-MailboxFolder.ps1 script today and I am not sure what has changed but I am unable to get it to run.

  1. I import the Web Services DLL like I normally do
    Import-Module -Name "C:\Program Files\Microsoft Office\root\Office16\ADDINS\Microsoft Power Query for Excel Integrated\bin\Microsoft.Exchange.WebServices.dll"

  2. Then I run the command to start archiving

  3. The script accepts the Auth Code as normal

After this, I get the below error message:
Exception setting "TraceListener": "Cannot convert the "EWSTracer" value of type "EWSTracer" to type "Microsoft.Exchange.WebServices.Data.ITraceListener"."
At C:\Users\gkosmas\Technical Documents\Office 365\Archive\Merge-MailboxFolder2-2.ps1:1929 char:13
$exchangeService.TraceListener = $script:Tracer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
FullyQualifiedErrorId : ExceptionWhenSetting

After this, I get this XML code repeating:

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
soap:Header
<t:RequestServerVersion Version="Exchange2010_SP2" />
</soap:Header>
soap:Body
<m:GetFolder>
<m:FolderShape>
<t:BaseShape>IdOnly</t:BaseShape>
<t:AdditionalProperties>
<t:FieldURI FieldURI="folder:DisplayName" />
<t:FieldURI FieldURI="folder:FolderClass" />
<t:FieldURI FieldURI="folder:ParentFolderId" />
<t:FieldURI FieldURI="folder:ChildFolderCount" />
<t:FieldURI FieldURI="folder:TotalCount" />
<t:ExtendedFieldURI PropertyTag="13825" PropertyType="Integer" />
</t:AdditionalProperties>
</m:FolderShape>
<m:FolderIds>
<t:DistinguishedFolderId Id="msgfolderroot">
<t:Mailbox>
<t:EmailAddress>[email protected]</t:EmailAddress>
</t:Mailbox>
</t:DistinguishedFolderId>
</m:FolderIds>
</m:GetFolder>
</soap:Body>
</soap:Envelope>

I have had this issue before where the DLL was the wrong version or it was not imported but everything seems to be in line on my side.

Any idea what might be the issue here?

Thank you in advance for your help here.

The specified object was not found in the store., Default folder Root not found.

HI David,

Im trying to Merge-Mailbox folders between two mailboxes,

.\Merge-MailboxFolder.ps1 -SourceMailbox $SourceMailbox -TargetMailbox $TargetMailbox -ProcessSubfolders -CreateTargetFolder -Copy -LogFile ".\CopyStatus.log" -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthSecretKey $secret

this command returns

[ErrorReported] ERROR (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The specified object was not found in the store., Default folder Root not found."
Failed to open target message store (NewMailbox@***.nl)

the only way I can get the script to connect, is using "-PathsRelativeToMailboxRoot" - but then it says its copying, yet nothing actually happens :)

also, is it possible to merge the two boxes together, but move the items in a subfolder on the new box, while keeping hierarchy ?

[MoveItems]FAILED TO LOCATE TARGET FOLDER

I have used this script many times. It has saved my life a lot.

Recently, I have had the script moving emails and then all of a sudden get multiple errors saying "[MoveItems]FAILED TO LOCATE TARGET FOLDER: " for each folder.

When I stop the script and start it again, it shows up throttling delay (which I understand is normal).

Not sure if something has changed that is causing this?

Merge-Mailboxfolder: Failed to load ADAL

Hi David,

Could you please help with issue missed ADAL, which is require for OAuth.
Where dll's can be found or in which installation these libraries are comes with.

Thanks,
Stas

A couple of suggestions

First item - for performance improvement, change line 958 from
Write-Progress -Activity $activity -Status "$processedCount of $itemCount item(s) read" -PercentComplete (($processedCount/$itemCount)*100)

To
if ($processedCount % 100 -eq 0) { Write-Progress -Activity $activity -Status "$processedCount of $itemCount item(s) read" -PercentComplete (($processedCount/$itemCount)*100) }

Reading in a lot of records and echoing that progress slowed down the discovery step quite a bit. This way, you get a bit better performance and a frequent-enough update on progress.

Second item - add a $MaximumToProcess parameter.

I cheated and just threw in a line 969:
If ($processedCount -gt 100000) { $moreItems = $false }

But ideally, you could do that as a parameter, have it default to 250k or some number like that, then work that into the discovery process and throw a message "found more items but capped to 250000" and change my suggested 969 line to use the variable feed.

Doing smaller chunks like that improved some performance aspects (didn't seem quite linear in the scaling for how long things took - did 50k chunks while could, then kicked off a bigger batch when just wanted it to run for a long stretch).

Thanks.

full_access_as_app missing

Hi David,

I've used the Merge-Mailbox script without issues when using API Delegated Permissions EWS.AccessAsUser.All.

This is fine for processing individual mailboxes, however i need to loop and process several mailboxes, this means it will auth on each mailbox, i understand that from another issue post you replied on means I'll have to switch to app auth.

When i've tried to do this it appears that i can't find 'full_access_as_app' in the list of the available API's, and when i edit the manifest file, it doesn't recognise it as an app (just displays the ID reference).

Does this mean the full_access_as_app has been deprecated and this script can no longer be ran using app auth?

This is the error i get when running the following

.\Merge-MailboxFolder.ps1 -SourceMailbox '[email protected]' -SourceArchive -ProcessSubfolders -CreateTargetFolder -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthSecretKey $secretKey -Impersonate

26/01/2024 10:56:57 [ErrorReported] ERROR (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The request failed. The remote server returned an error: (403) Forbidden."
Failed to open source message store ([email protected])
Please check that you have impersonation permissions

(I've given my account ApplicationImpersonation via an Exchange Online role, but not 100% sure if that error is just linked to full_access_as_app not having API perms?)

Any help would be appreciated, thank you.

Missing $ in Merge-MailboxFolder script at line 371

Hi David,

This is great tool and helps us a lot. In the latest version, 1.3.1, we find it can't run using certification.

  1. Seems you missed a $ at line 371 in GetTokenWithCertificate function.

function GetTokenWithCertificate
{
# We use MSAL with certificate auth
if (!script:msalApiLoaded) <===== should be if (!$script:msalApiLoaded)
{
$msalLocation = @()
$script:msalApiLoaded = $(LoadLibraries -searchProgramFiles $false -dllNames @("Microsoft.Identity.Client.dll") -dllLocations ([ref]$msalLocation))
if (!$script:msalApiLoaded)
{
Log "Failed to load MSAL. Cannot continue with certificate authentication." Red
exit
}
}

  1. after adding the $, I failed in line 351, in LoadLibraries function.
    try
    {
    LogVerbose ([string]::Format("Loading {2} v{0} found at: {1}", $dll.VersionInfo.FileVersion, $dll.VersionInfo.FileName, $dllName))
    Write-Host "debug here1" -ForegroundColor Yellow
    Add-Type -Path $dll.VersionInfo.FileName
    if ($dllLocations)
    {
    $dllLocations.value += $dll.VersionInfo.FileName
    ReportError
    }
    }
    catch
    {
    ReportError "LoadLibraries"
    return $false
    }

Error is like below:

Try to run Add-Type manually to get LoaderExceptions:
PS C:\Users\hongzhou\Downloads\MergeFolderTest> try {
Add-Type -Path C:\Users\hongzhou\Downloads\MergeFolderTest\Microsoft.Identity.Client.dll
}
catch {
Write-Host "Message: $($.Exception.Message)"
Write-Host "StackTrace: $($
.Exception.StackTrace)"
Write-Host "LoaderExceptions: $($_.Exception.LoaderExceptions)"
}
Message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
StackTrace: at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at Microsoft.PowerShell.Commands.AddTypeCommand.LoadAssemblyFromPathOrName(List`1 generatedTypes)
at Microsoft.PowerShell.Commands.AddTypeCommand.EndProcessing()
at System.Management.Automation.CommandProcessorBase.Complete()
LoaderExceptions: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

I've put these dlls within the same folder.
Mode LastWriteTime Length Name


d----- 2023/10/18 17:07 Microsoft.IdentityModel.Abstractions.6.22.0
d----- 2023/10/18 17:10 System.Runtime.4.3.1
-a---- 2023/10/18 15:17 91328 Merge-MailboxFolder.ps1
-a---- 2021/11/19 2:44 108504 Microsoft.Identity.Client.Desktop.dll
-a---- 2023/4/14 16:39 1632728 Microsoft.Identity.Client.dll
-a---- 2021/11/19 2:44 1524176 Microsoft.Identity.Client.dll.37
-a---- 2023/9/8 16:17 1600968 Microsoft.Identity.Client.dll.new
-a---- 2023/3/28 14:12 65928 Microsoft.Identity.Client.Extensions.Msal.dll
-a---- 2022/7/27 11:08 18824 Microsoft.IdentityModel.Abstractions.dll
-a---- 2023/9/8 16:17 1081728 Microsoft.IdentityModel.Clients.ActiveDirectory.dll
-a---- 2023/9/8 16:17 89480 Microsoft.IdentityModel.JsonWebTokens.dll
-a---- 2023/9/8 16:17 34224 Microsoft.IdentityModel.Logging.dll
-a---- 2023/9/8 16:17 989064 Microsoft.IdentityModel.Tokens.dll

Please help, thanks.

Overwrite vs Add Calendar Items

Can you enhance your powershelgl script to allow for overwriting based on Subject and Start Date being the same as what that person has in their calendar already? We have a scenario where we are pushing the company holidays to everyone's calendars. Your script works awesome to bring it in the first time but I don't want to rerun the script and get duplicates. I would rather it ignore it if it already exists. It could simply be a flag that doesn't allow it to place duplicates on the calendar if it already exists.

Thanks,
Jason

Modern Authentication

Hi! I love this script and have been using it for months without any problems. But unfortunately it doesn't work since a couple of days. I think this is due to the type of authentication which is used. Since Oct 1st, MS set the "modern" authentication as requirement for lots of things.

At the moment, the script fails on the following line:
$CalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($service, [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar);
-> Error 401.

I just ran a connectivity test via https://testconnectivity.microsoft.com/tests/O365EwsAccess/input . When I run the test with my username and password, a specified target mailbox and "Calendar" as target folder I get:

  • The same error when using the standard authentication
  • No error when using OAuth
    -> So I guess the script has to be changed in order to incorporate the modern authentication.

Can anybody please tell me what exactly has to be changed?
Thanks in advance and kind regards

correct syntax to "unarchive" everything back to the primary mailbox? (Exchange Online/365)

Hi @David-Barrett-MS and thank you for the excellent-looking script! 🙏

I am trying to wrap my head around the syntax and am a bit afraid to execute a command that might mangle someone's mailbox, so I'm hoping you can advise:

I want to move "everything" (all folders + subfolders) with the exception of system folders such as "Conversation Action Settings", "Top of Information Store", Recoverable Items" etc. back to the user's primary mailbox. Once it's done I intend to disable the Archive for him. I understand this will destroy the data in the archive after 30 days, so I want to be sure I move everything.

It seems the closest example would be your Example 5. But I think that will only take "Inbox" and "Sent Items". Is there a variant I can use to grab any & all other arbitrarily-named folders he may have in his archive? I put a note on issue #6 but that seems incorrect too.

Thank you kindly.

Merge-MailboxFolder - Online Archive EXO

Is it possible to merge mails from the primary mailbox to the exchange online archive of the same user?
If i select -TargetArchive, the script doesn't find the target message store. I think this parameter is only for the Outlook Archive folder?

Microsoft 365 Authentication Issue

It looks like the URL in the script for Microsoft 365 authentication may be out of date. Getting a 404 error when using -Office365 and -OAuth

Merge-MailboxFolders various issues (v1.3.0 / 1.3.2)

Hi David, this had been working great until last week, we can no longer get mail moving out of mailboxes into their archive.

Q: If user has MFA enabled, will this still work? We have a number of users (including myself) who have MFA enabled now.

Script v1.3.0 / Microsoft.Identity.Client 4.45.0 / Microsoft.Exchange.WebServices v15.00.0913.015

If we try and use v1.3.0 to run as a job, that appears to have stopped working (it did this previously and you fixed it with v1.3.0).

#30

#28

I've tried using v1.3.2 but same issues around job use and other issues. I've attached some logs which may help show what is going on, v1.3.0 and v1.3.2

Both curently stop with an error around a null-value - it ran previously through the mailbox OK, but latest runs now throw this error as shown in error txt attachment.

When ran interactively, the mailbox is processed but nothing has been actually moved, e.g. Inbox has 760 items in it and after a run, still contains 760.

I've attached a few logs from runs using 1.3.0 and 1.3.2 for comparison, the commandline that calls your script is in the 4. file
Error_Logs.zip

As an additional note, the permissions model for our admin accounts also changed, we now have to use PIM to apply Exchange Administrator rights (which we run the script under). To build the folder list from Exchange Online cmdlets, I would have thought that was enough? We get the elevated session for a set period of time (on the order of hours). I've ran these all after PIM has been applied for at least an hour.

How to Merge-MailboxFolder - move everything from Archive to Archive Folder in Inbox.

I'm trying to collapse our archives back into an Archive folder in users inboxes. I can't figure out how to move the entirety of the Archive to an archive folder in the inbox while still maintaining the folder structure under the new archive folder under the inbox?

I've tried -MergeFolderList @{"Archive",@("*")}
I've tried -MergeFolderList @{"Archive",@()}
I've tried -MergeFolderList @{"Archive",@("WellKnownFolder")}

Merge-Mailbox issue with copy/move emails

Hi,

Could you please help me figured out what might cause this issue.
I'm using impersonate feature and got this error:
No matching items were found
[MoveItems]Copying from st***@:\Top of Information Store\Inbox to sta@:\Top of Information Store\Inbox
2 items found; attempting to copy
Permanent error ErrorToFolderNotFound reported for item: AQMkADhlOGE4MGY0LWY5NTMtNDA3Zi1hYzdlLWU2YTE0MmI1MzkxYQBGAAADlBaV8KjmcUi0WBTt4kP6hwcAjuo13kTFdE+l+AIOL3oMVwAAAgEMAAAACSUY2EAcGUSu4dB5E3TE3wAAAjC9AAAA
2 items reported error during batch request (if throttled, some failures are expected, and will be retried)
Permanent error ErrorToFolderNotFound reported for item: AQMkADhlOGE4MGY0LWY5NTMtNDA3Zi1hYzdlLWU2YTE0MmI1MzkxYQBGAAADlBaV8KjmcUi0WBTt4kP6hwcAjuo13kTFdE+l+AIOL3oMVwAAAgEMAAAACSUY2EAcGUSu4dB5E3TE3wAAAjC8AAAA
1 items reported error during batch request (if throttled, some failures are expected, and will be retried)
[MoveItems]st***@****:\Top of Information Store\Inbox processed, now contains 2 items(s)

If using script without this feature everything works fine, but I can't move/copy items for mailboxes which not belongs to me.

Thanks,
Stas

Autodiscover service couldn't be located error (MergeMailboxFolder)

I have used the script in the past to move emails from archive to inbox in the past along with a batching script to perform the action on multiple accounts in the past. I tried again today and getting the following errors using the script:

The [email protected] is the account that we are trying to move emails from archive to inbox, and administrator.O365 is the account that has full access to this mailbox.

PS C:\ArchiveMerge>> .\Merge-MailboxFolder.ps1 -SourceMailbox [email protected] -SourceArchive -TargetMailbox
 [email protected] -ProcessSubfolders -MergeFolderList @{"WellKnownFolderName.Inbox"= "Inbox"} -AllowInsecureRedi
rection -Verbose -Credential (Get-Credential)

cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential

Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your
computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning
message. Do you want to run C:\EOL-ArchiveMerge\Merge-MailboxFolder.ps1?
[D] Do not run  [R] Run once  [S] Suspend  [?] Help (default is "D"): R
Merge-MailboxFolder.ps1 version 1.2.2 starting
VERBOSE: Loading Microsoft.Exchange.WebServices.dll vSystem.Object[] found at: System.Object[]
Using EWS Managed API found at: C:\Program Files (x86)\Microsoft Office\root\Office16\ADDINS\Microsoft Power Query for E
xcel Integrated\bin\Microsoft.Exchange.WebServices.dll

Processing mailbox [email protected]
VERBOSE: Applying given credentials: [email protected]
VERBOSE: Performing autodiscover for [email protected]
[email protected] : error occurred during autodiscover: Exception calling "AutodiscoverUrl" with "2" argument(s):
 "The Autodiscover service couldn't be located."
Failed to connect to source mailbox

The last version I was using was 1.1.5 and I believe it still worked about 2 months ago. Any assistance in finding the issue would be appreciated. I am not very well versed in PS scripting.

Thank you for the help and the script.

Calendar in a Public Folder

I find these scripts very useful. My task is to export appointments from a calendar of a public folder of a server on-premises.
However, it's not clear to me how the parameters should be used.

I use -IgnoreSSLCertificate -PublicFolders -FolderPath $publicFolderPath -Credential $credential -EwsUrl $ewsUrl -StartsAfter $startsAfterDate -EndsBefore $endsBeforeDate -ExportCSV $csvFile -LogFile $logFile

The folder path is \ABCD\Intranet and Intranet is a calendar type folder.
grafik

However, when called, the script always accesses my mailbox and as a result I get the following error message:
_Fehler beim Aufrufen der Methode, da [System.String] keine Methode mit dem Namen "FindItems" enthält.
In Z:\Gruppe Datenverarbeitung\IT-Dokumentationen\Webserver\Intranet-Kalender\Search-Appointments.ps1:1175 Zeichen:13

  •         $results = $Folder.FindItems($searchFilter, $view)
    
  •         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : MethodNotFound_

With the same parameters, but with -Mailbox, I get the desired result.

Error when I use application login

Hi I get this error when I copy the redirect url its set to local

04/12/2023 14:25:14 [ErrorReported] ERROR (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized."
Failed to open source message store ([email protected])

Use mailboxGUID for source and target

Hello, I was wondering if it was possible to use this script to specify a source and target mailbox using the mailbox GUID?
Scenario:
I have some users on EXO that have multiple mailbox locations (auxarchives) and this is causing us issues, so I wanted to basically merge the data from the other aux archives into the primary archive. For example, user [email protected] has 3 mailbox locations
primary - 20gb
archive - 60gb
auxarchive - 24gb

I would like to migrate/merge all the data in the auxarchive to the primary archive (all on exo) and disable the auxarchive. The whole reason for this is because i have to prepare some of my users to be migrated to our new tenant, but since they had auto expanding at one point they are unable to be cutover and this is causing us major headache. help would be appreciated!

What to do with uncopied files?

Hi,

first of all - thank you for this marvellous script. Really helps with users without self-mailbox-control ;)

I'm copying a emails with the following command:

$src = "[email protected]"
$dst = "[email protected]"
$start = "12/31/2020"
$end = "01/01/2022"
.\Merge-MailboxFolder.ps1 -SourceMailbox $src -TargetMailbox $dst -OnlyItemsCreatedAfter $start -OnlyItemsCreatedBefore $end -SourceArchive -CreateTargetFolder -ProcessSubfolders -Office365 -OAuth -OAuthTenantId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

and I get the following:

08.02.2024 15:10:25 [MoveItems] [MoveItems]Moving from [email protected]:\Folder nadrzędny magazynu informacji\Elementy wysłane to [email protected]:
\Top of Information Store\Elementy wysłane
**08.02.2024 15:10:26 [MoveItems] 2534 items found; attempting to move**
08.02.2024 15:12:06 [RemoveProcessedItemsFromList] No results returned - assuming all items processed
(...)
08.02.2024 18:09:10 [Merge-MailboxFolder.ps1] Script finished in 02:59:03.7367093

No matter how many times I run the script there are still those 2534 items. Is there any workaround or parameters to add to deal with this? :)

Issues with Search Results in Update FolderItems.ps1

Hello David,

Hope you are doing good.
I have below issues below.

When i run the below command

$items = .\Update-FolderItems.ps1 -Mailbox $Mailbox -FolderPath "WellKnownFolderName.MsgFolderRoot" -ProcessSubfolders -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthRedirectUri $redirectUrl -OAuthSecretKey $secretKey -SearchFilter "subject:Invoice" -ListMatches

Issue 1 :
When i check $items | fl it only shows the subject of the emails and other fields are empty, like timedaterecieved, sender, recipient.

Issue 2:
When i am satisfied with the search results in -listmatches , how can pass the values of $items with -delete -harddelete without running the entire command which will perform the search again.

Thank you in Advance

Merge MailboxFolders - how to specify folder path and auth fails

Some background on this:

A nasty bug that Microsoft refuses to fix (they deem it to be 'by design'): Can't use Outlook to move a folder tree (a folder that contains subfolders) from one folder to another in a Shared Mailbox. Get the bogus error 'cannot move/copy folder because it may contain private items'. OWA can't be used because the folder structure on the source/target mailbox is hierarchical and complex. When it prompts with the target, it does an 'expand all' on the folders and it's impossible to locate the folder among thousands of nested folders - no option to avoid the 'expand all' or 'collapse' the folder list.

2 issues:

  1. I've tried every possible combination of authentication parameters ('-oauth', '-office365' with or without 'credential (get-credential)', etc. I'm already logged into the MS acct associated with the mailboxes. I either get 'Failed to obtain OAuth token', or 'Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized." Failed to open source message store ([email protected])
  2. How to specify folder path? The path is not a 'wellknownfoldername'. I tried using a folder path I've used successfully with VBA code: "\<folder><subfolder>, but I don't know if that's the proper syntax - can't determine because blocked with the above authentication errors.

Works for some but not all mailboxes... perhaps a folder config issue?

David,
First of all, thank you for all of your work on these scripts over the years - they are truly valuable to us admins.

I have been converting my scripts to use your updated versions to work with Oauth but I've found an issue where some of the mailboxes in my tenant cannot be 'found' although, I'm certain they exist.

For the affected mailboxes that I've found so far, it throws two different errors (likely the related or the same) for each script.

With the merge script, I'll get:
Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The specified object was not found in the store., Default folder Root not found." Failed to open target message store (***redacted***)

With other dedupe script, I'll get:
Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The specified object was not found in the store., Default folder Root not found." Failed to find folder WellKnownFolderName.MsgFolderRoot

Like I said, this doesn't happen for all mailboxes so I'm curious if you are aware of this issue and/or if you have any workarounds that I can try.

Many thanks!

[GetTokenWithCertificate] Failed to load MSAL. Cannot continue with certificate authentication.

I try to use certificate auth with latest script 1.3.2

2023/10/24 10:43:34 [Merge-MailboxFolder.ps1] Merge-MailboxFolder.ps1 version 1.3.2 starting
VERBOSE: Loading Microsoft.Exchange.WebServices.dll v15.00.0913.015 found at: C:\Users\hongzhou\Downloads\MergeFolderTest\Microsoft.Exchange.WebServices.dll
2023/10/24 10:43:34 [LoadEWSManagedAPI] Using EWS Managed API found at: C:\Users\hongzhou\Downloads\MergeFolderTest\Microsoft.Exchange.WebServices.dll

Processing mailbox [email protected]
VERBOSE: Loading Microsoft.Identity.Client.dll v4.57.0.0 found at: C:\Users\hongzhou\Downloads\MergeFolderTest\Microsoft.Identity.Client.dll
VERBOSE: Requesting token using certificate auth
New-Object : A constructor was not found. Cannot find an appropriate constructor for type Microsoft.Exchange.WebServices.Data.OAuthCredentials.
At C:\Users\hongzhou\Downloads\MergeFolderTest\Merge-MailboxFolder.ps1:634 char:28

  • ... edentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCrede ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
    • FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

Failed to connect to source mailbox
2023/10/24 10:43:35 [Merge-MailboxFolder.ps1] Script finished in 00:00:01.1597260

I put all dlls within same folder.
Mode LastWriteTime Length Name


-a---- 2014/12/20 2:02 1130264 Microsoft.Exchange.WebServices.dll
-a---- 2023/10/17 7:26 1654384 Microsoft.Identity.Client.dll
-a---- 2022/7/27 11:07 18832 Microsoft.IdentityModel.Abstractions.dll

all dlls are from nuget install
nuget.exe install Microsoft.Identity.Client
nuget.exe install Microsoft.Exchange.WebServices

Please help check, thanks.

moving items inside the same mailbox

My apologies if i am asking the obvious, ive been frying my brain over this one for the past week.

I am dealing with "a migration gone wrong" situation where there's problem with the language settings. Originally everything was in Dutch, so "Postvak In, Verzonden Items, Kalender". After a migration from pst files everything new is in "Inbox, Send Items, Calendar".

And i am unsure how to use MergeFolder.ps1 to merge two folders in the same mailbox?

Import-CalendarCSV.ps1

Hey David, I've been using your scripts as samples when answering questions on the different communities for years now, so first of all thanks for those. Can you please upload the Import-CalendarCSV.ps1 one to your repo? There are still some copies circulating on the net, but I prefer to use the original :)

Merge-MailboxFolders Throttling Handling

Hi David - Thanks for the awesome script. I am running in to an issue where after the throttling stall , when the job resumes - it is skipping the remaining items in the current folder.

1040 items found; attempting to move
Throttling detected, server requested back off for 191680 milliseconds
Throttling budget should now be reset, resuming operations
No results returned - assuming all items processed

Throttle_merge_mailboxfolders

Merge-MailboxFolder.ps1 - failed to obtain token

Hi David,
I get an error message at the point when i paste in the URL required to generate the authentication code.
Can you confirm what value is meant by "paste the redirect URL (including auth code)"? Is it not the value generated in the browser window? Would appreciate any urgent input on this.
MergeFolderIssue.docx

PS C:\temp\Specs> .\Merge-MailboxFolder.ps1 -Copy -WhatIf -SourceMailbox [email protected] -TargetMailbox [email protected] -MergeFolderList @{"WellKnownFolderName.Inbo
x"= "Inbox"; "WellKnownFolderName.SentItems"= "Sent Items"} -ProcessSubfolders -CreateTargetFolder -Office365 -OAuth -OAuthClientId "e3b3c4df-e041-4613-a66d-535309299948" -OAuthTenantId "01088
aa4-1bdc-42ad-a76a-17ef028779fc"
Merge-MailboxFolder.ps1 version 1.2.5 starting
Using EWS Managed API found at: C:\Program Files\Microsoft\Exchange Server\V15\Bin\Microsoft.Exchange.WebServices.dll

Processing mailbox [email protected]
Please complete log-in via the web browser, and then paste the redirect URL (including auth code) here to continue
Auth code: http://localhost/code?code=0.AV4ApIoIAdwbrUKnahfvAod5_N_Es-NB4BNGpm1TUwkpmUheAAA.AgABAAIAAAD--DLA3VO7QrddgJg7WevrAgDs_wUA9P-nkH3P6arHA3BUNwmWFwc7-soYGZJoHnD8ryRMEutMSuVQwljMiMrELlOf
g2s6jvQ2LFtMrxVDymOL9K3t2UkuVJXM22xmqADVKqWWeho-Jx5YfcRQmkHszNcT3e9SABRUIc9Tas_CvGFGTozk7BibtSVi-Fuk_q8sApFcaHoHXfOtq5lyTHKxbLjw0OZfSlrw6G7jayvd_90X15CXEJMtrioybLjhYRjqRkU0t4NfD1sX32oQpdymNok0
O0vZuEr3zexk_xoCbCEGvkvr3To9EsgzayaaoFWLOlxo9Reji_Su1fM46ga1q6VH__M-EkFW-jfE3QKxwipNOrHTQO6g2yXblv08WDO372SQGi35e5ESKovZv-S8GWHUQB8VJC3raixe92Hms9F_5E2yKCwfWt4BJF__v7VV7WaYymIz5ydvDq73KvCwFJtn
JuBM5vHvu8Qr1aeLAspBLOlxVPfhxli_oHyeUd-W5O0ZnnEEtPUm23RPp6HD6hG0vZ-MB3oaOwUGMHRzxwRpVX3C7Qq4TO4GNNMqwuoHTJTQ6ETxVSTp4Ix71KUsk9duQ0-ShjJWgpMEZ9Gjir6y-h04mQrV9dhBNfTOLriiK3Z6NIn5Yipi-Pdn4jABhIjO
emi0lzJEX4bLQgzg1HtdDhyECa223XhGGXKzV0vKqAIhOJ_7Tsdf_wSJA-RYesoZmFhvmf2BbBAG5vY6Aoy-jbezbO2fVfKeoIf5K_FECv5lXY1we5nvKVvS1OHAftEfqBpZewXmme7tc1yBGSXXh7nHJQOiB_FzS66cm-rwxpO9apjd8LR81l7UQUaepg&s
ession_state=a9adf59b-b7df-4a67-8e84-a7be47946d9b
Failed to obtain OAuth token

Remove-DuplicateItems two questions

I want to say thank you, I have been able to use the merge-mailboxfolders.ps1 successfully, but I am running into issues running Remove-DuplicateItems using Oath. Please see below.

.\remove-duplicateitems -mailbox $mailbox -archive -recursefolders -Office365 -OAuth -OAuthClientID $oathclientid -OauthTenantId $oath -VerboseLogFile -logfile c:\temp\remove_duplicates.log -EwsUrl $ewsurl -whatif
Remove-DuplicateItems.ps1 version 1.1.1 starting
Using EWS Managed API found at: C:\repos\Powershell-EWS-Scripts\Legacy\Microsoft.Exchange.WebServices.dll
Processing mailbox [email protected]
Unable to load locate
Failed to load ADAL, which is required for OAuth

  1. The instructions say to use -OathSecretKeyID but that parameter isn't available.
  2. When I run the script, I receive this error.
    Unable to load locate
    Failed to load ADAL, which is required for Oath

multiple mailboxes

Sorry if my question is too stupid, but I can't find a key to move items from Archive to Main mailbox for Multiple mailboxes,
but descriptions say "It can be used for multiple folders, and automated against multiple mailboxes. "
Could you tell me please what the method for that?

Merge-Mailboxfolder Impersonation error

Hi David,

Thanks for creating this script to move mails from mailbox to mailbox.
I have tried using this but encountered the errors below:

Merge-MailboxFolder.ps1 version 1.1.9 starting
VERBOSE: Loading Microsoft.Exchange.WebServices.dll vSystem.Object[] found at: System.Object[]
Using EWS Managed API found at: C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll

Processing mailbox [email protected]
VERBOSE: Using default credentials
VERBOSE: Currently caching 1 ExchangeService objects
VERBOSE: [ThrottledFolderBind]Attempting to bind to folder MsgFolderRoot ([email protected])
Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The request failed. The remote server retur
ned an error: (401) Unauthorized."
VERBOSE: FAILED to bind to folder MsgFolderRoot ([email protected])
Failed to open source message store ([email protected])
Please check that you have impersonation permissions

I have confirmed that the user running has ApplicationImpersonation rights.
Is there any other place that I should check?

Merge-MailboxFolder script | Folder hierarchy copied but not the content

Hello @David-Barrett-MS,

Thank you for your great scripts!

I have run the following command:
.\[Merge-MailboxFolder.ps1 -SourceMailbox <SOURCE_MAILBOX> -TargetMailbox <TARGET_MAILBOX> -TargetArchive -MergeFolderList @{"Inbox"= "WellKnownFolderName.Inbox"; "Sent Items"= "WellKnownFolderName.SentItems"} -ProcessSubfolders -CreateTargetFolder -Office365 -Impersonate -OAuth -OAuthClientId <OAUTH_CLIENT_ID> -OAuthTenantId <OAUTH_TENANT_ID> -OAuthSecretKey <OAUTH_SECRET_KEY> -Copy -LogFile ./test_mailboxmerge2.log

If I check the target, I notice that the folders are created, but, although logs show that items are copied:

"2 items found; attempting to copy
No results returned - assuming all items processed"

I don't see the contents in the folders.

Do you have any idea?

Thank you and best regards,

Bertrand Pons

Merge-MailboxFolder Permissions

Hi David, trying to get this script working with certificate authorisation and think I'm struggling with permissions that need to be on the app registration.

image

I have that set at the moment. The cert itself works fine against another app registration I have (it connects to the mailbox fine), and script works fine when using the secret key method, I am just swapping -OauthSecretKey for -OAuthCertificate on the command line.

The script attempts to build the list of items to move, but seems to fail: Error when querying items: You cannot call a method on a null-valued expression.

I am using Microsoft.Identity.Client.dll v4.45.0.0 (anything later fails)

Processing mailbox

hi,
I am running the script, but without result. See below. It starts and then shows "processing mailbox" within a few seconds.
What can be the issue?

I checked the mailbox and it has deleted items in recovery.

PS C:\temp> .\RecoverDeletedItems.ps1 -Mailbox "[email protected]" -archive -RestoreToFolder "Archive" -LogFile "c:\temp\log.txt" -EwsUrl "https://outlook.office365.com/EWS/Exchange.asmx"
RecoverDeletedItems.ps1 version 1.1.4 starting

Using EWS Managed API found at: C:\Program Files (x86)\Microsoft Office\root\Office16\ADDINS\Microsoft Power Query for Excel Integrated\bin\Microsoft.Exchange.WebServices.dl
l

Processing mailbox [email protected]

Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The specified object was not found in the store., Default folder Root not found.

Hello @David-Barrett-MS,

Thank you for your great scripts!

What I would like to achieve in Exchange Online is to copy folders from on mailbox to another mailbox in two parts.
Because license user's is EOL.
First part, copy mailbox A in the mailbox B.
Second part, copy archive mailbox A in the another archive mailbox B.

Thus, when I run the script Merge-MailboxFolders.ps1:

.\Merge-MailboxFolder.ps1 -SourceMailbox $SourceMailboxA -TargetMailbox $SourceMailboxB -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthRedirectUri $redirectUrl -Copy -ProcessSubfolders -OAuthSecretKey $secretKey -CreateTargetFolder -Impersonate

.\Merge-MailboxFolder.ps1 -SourceMailbox $SourceMailboxA -SourceArchive -TargetMailbox $SourceMailboxB -TargetArchive -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthRedirectUri $redirectUrl -Copy -CreateTargetFolder -ProcessSubfolders -OAuthSecretKey $secretKey

I get the following output:

Merge-MailboxFolder.ps1 version 1.2.6 starting
Using EWS Managed API found at: C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll

Processing mailbox SourceMailboxA
Error (ThrottledFolderBind): Excepción al llamar a "Bind" con los argumentos "3": "The specified object was not found in the store., Default folder Root not found."
Failed to open target message store (SourceMailboxB)

Merge-MailboxFolder.ps1 version 1.2.6 starting
Using EWS Managed API found at: C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll

Processing mailbox SourceMailboxA
Error (ThrottledFolderBind): Excepción al llamar a "Bind" con los argumentos "3": "Access is denied. Check credentials and try again., Archive mailbox:f9db971c-dfd6-4b6e-89aa-af4652bdb695"
Failed to open target message store (SourceMailboxB)

Do I have missed something related to permissions?

Thank you in advance.

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

Hello @David-Barrett-MS,

Thank you for your great scripts!

What I would like to achieve in Exchange Online is to move folders from on shared mailbox to another shared mailbox in its archive.

Thus, when I run the script Merge-MailboxFolders.ps1:

.\Merge-MailboxFolders.ps1 -SourceMailbox <SOURCE_MAILBOX> -TargetMailbox <TARGET_MAILBOX> -TargetArchive -MergeFolderList @{"Inbox"= "WellKnownFolderName.Inbox"; "Sent Items"= "WellKnownFolderName.SentItems"} -ProcessSubfolders -CreateTargetFolder -Office365 -OAuthClientId <OAUTH_CLIENT_ID> -OAuthTenantId <OAUTH_TENANT_ID> -OAuthSecretKey <OAUTH_SECRET_KEY> -WhatIf

I get the following output:

Merge-MailboxFolders.ps1 version 1.2.3 starting
Using EWS Managed API found at: C:\Program Files (x86)\Microsoft Office\root\Office16\ADDINS\Microsoft Power Query for Excel Integrated\bin\Microsoft.Exchange.WebServices.dll

Processing mailbox <SOURCE_MAILBOX>
Error (ThrottledFolderBind): Exception calling "Bind" with "3" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized."
Failed to open source message store (<SOURCE_MAILBOX>)

If I add '-Impersonate' parameter, I get the same error with this additional error: Please check that you have impersonation permissions

Do I have missed something related to permissions?

Thank you in advance.

Can't Move Calendar/Tasks Items from Primary Mailbox to Archive

Same issue as happened earlier in the year - will raise a MS Ticket for it also. ErrorMoveCopy when moving items from Calendar/Tasks folder into Archive.

I've realised while working on this issue that this is causing multiple copies of Calendar/Task items to be created in the Archive folder because it can't remove the original. Every time we run the script it just creates a new copy of the item in the archive.

Merge-MailboxFolders

Hi, David. I've been tweaking the list of folders that I'm moving into the archive for the users we offboard, but have hit a snag with the Deletions folder. As you (may) recall, we need to shrink the primary mailbox down to as small as possible before we offshore it.

I am almost certain this used to work fine, but can't seem to get it to recognise the Deletions folder anymore. We do occasionally get users who've got a substantial amount of mail in there that is recoverable, so we want to move it out to the archive. When the user is later moved back into M365, we just leave it in the archive and it's permanently gone when we then remove their archive.

Any idea why it can't recognise this folder path? If I do it as part of the full folder collection or specify it separately like below when I have been troubleshooting it's the same error.

image

Update Folder : Unable to bind to root folder. No further processing possible / If accessing a mailbox that has MFA enabled, you must use OAuth

Hi,
I'm trying to delete some weekly meetings organized by soemone which no longer exists.
.\Update-FolderItems.ps1 -Mailbox $Mailbox -Office365 -OAuth -OAuthTenantId $tenantId -OAuthClientId $clientId -OAuthRedirectUri $redirectUrl -PropertiesMustMatch @{"0x0037001F" = "Standup Meeting It-Cloud"} -Delete -WhatIf

I have 2 errors when i want to use "Update Folder" script

20/11/2023 11:29:46 [ProcessMailbox] Unable to bind to root folder.  No further processing possible.
20/11/2023 11:29:46 [ProcessMailbox] If accessing a mailbox that has MFA enabled, you must use OAuth

I can't resolve those problems

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.