skip to Main Content

Delete folder in Exchange Online from all mailboxes

Do you want to delete a folder from all mailboxes in Exchange Online with PowerShell? To make it more interesting, what if you want to delete specific folders and target specific mailboxes. Impressive on how to achieve that, right? This article will teach you how to delete folders in Exchange Online from all mailboxes.

Before you start to delete folders in Exchange Online

Follow the steps carefully, as shown in the article to:

  • Delete specific folder/folders from specific mailboxes in Exchange Online
  • Delete specific folder/folders from all mailboxes in Exchange Online

Add impersonation rights in Exchange Online

Use impersonation when you have a service application that needs to access multiple mailboxes and “act as” the mailbox owner. Read more about impersonation and EWS in Exchange.

Create and add impersonation rights to the account that is going to run the script. It can be a global admin account or a service account. In our example, the global admin account is added.

Log in to Exchange Admin Center (Exchange Online). In the feature pane, click on permissions and follow with admin roles in the tabs. Click the + icon in the toolbar to create a new role group.

Delete folder in Exchange Online from all mailboxes add role group

Give the new role group a name — for example, Application-Impersonation. Assign the role of Application-Impersonation. Add yourself, the global admin, or a service account that you created as a member. Click Save when done.

Delete folder in Exchange Online from all mailboxes new role group

The role group Application-Impersonation is created successfully. Good to know is that it can take up to an hour before the changes are applied.

Delete folder in Exchange Online from all mailboxes role group created

The next step is to install Microsoft Exchange Web Services Managed API 2.2.

Microsoft Exchange Web Services Managed API 2.2

Download and install Microsoft Exchange Web Services Managed API 2.2. Download from here (Microsoft) or here (direct link). Save the file to the system.

Delete folder in Exchange Online from all mailboxes download Microsoft EWS Managed API

Run the setup as administrator and install Microsoft Exchange Web Services Managed API 2.2.

Delete folder in Exchange Online from all mailboxes install EWS Managed API

After installing, verify in the installation path that you can see the files.

Delete folder in Exchange Online from all mailboxes verify installation files EWS Managed API

The next step is to create the text files.

Create text files for the script

Create three text files in the C:\Temp folder.

  1. Folders.txt
  2. Log.txt
  3. Users.txt
Delete folder in Exchange Online from all mailboxes create text files

Open Folders.txt and add FolderName at the top. Add the folder names on each line. In our example, we like to delete four folders in the mailboxes.

The script will generate logs and place them in the Log.txt file. Keep it empty.

Open Users.txt and add EmailAddress in the top. Add the email addresses on each line. The script will delete the folders from these mailboxes.

Read more: Export a list of mailboxes to CSV file »

The next step is to download the PowerShell script.

Prepare the Delete Folders Exchange Online PowerShell script

Download the Delete-Folders-EXO.ps1 PowerShell script and save it to the C:\Scripts folder.

<#
    .SYNOPSIS
    Delete-Folders-EXO.ps1
	
    .DESCRIPTION
    Delete specific folder/folders from specific mailboxes in Exchange Online.

    .LINK  
    alitajran.com/delete-folder-in-exchange-online-from-all-mailboxes

    .NOTES
    Written by: Catalin Streang
    Edited by:  ALI TAJRAN
    Website:    alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .LICENSE
    The MIT License (MIT)
    Copyright (c) 2020 ALI TAJRAN
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    .CHANGELOG
    V1.00, 10/09/2020 - Initial version

    .REQUIRED
    The script requires EWS Managed API 2.2, which can be downloaded here: https://www.microsoft.com/en-gb/download/details.aspx?id=42951 
    Make sure the Import-Module command matches the Microsoft.Exchange.WebServices.dll location of EWS Managed API, chosen during the installation
#>

[string]$info = "White"                              # Color for informational messages
[string]$warning = "Yellow"                          # Color for warning messages
[string]$error = "Red"                               # Color for error messages
[string]$LogFile = "C:\Temp\Log.txt"                 # Path of the Log File
[string]$FoldersCSV = "C:\Temp\Folders.txt"          # Path of the Folders File
[string]$UsersCSV = "C:\Temp\Users.txt"              # Path of the Users File

function DeleteFolder($MailboxName) { 
    Write-Host "Searching for folder in Mailbox Name:" $MailboxName -foregroundcolor $info
    Add-Content $LogFile ("Searching for folder in Mailbox Name:" + $MailboxName) 

    # Change the user to impersonate
    $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

    do { 

        $oFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 

        $oFolderView.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep

        $oSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $FolderName) 

        $oFindFolderResults = $service.FindFolders([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot, $oSearchFilter, $oFolderView) 

        if ($oFindFolderResults.TotalCount -eq 0) {
            Write-Host "Folder does not exist in Mailbox:" $MailboxName -foregroundcolor  $warning
            Add-Content $LogFile ("Folder does not exist in Mailbox:" + $MailboxName) 
        } 
        else { 
            Write-Host "Folder EXISTS in Mailbox:" $MailboxName -foregroundcolor  $warning
            Add-Content $LogFile ("Folder EXISTS in Mailbox:" + $MailboxName) 

            $oFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $oFindFolderResults.Folders[0].Id) 

            Write-Host "Deleting Folder:" $FolderName -foregroundcolor  $warning
            Add-Content $LogFile ("Deleting Folder:" + $FolderName)

            # You can choose from a few delete types, just choose one:
            $oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
            #$oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
            #$oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems)
        } 

    } while ($oFindFolderResults.TotalCount -ne 0) 

    $service.ImpersonatedUserId = $null

}
Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll" 

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2013_SP1

# Provide the credentials of the O365 account that has impersonation rights on the mailboxes declared in Users.txt
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList (Get-Credential)

# Exchange Online URL
$service.Url = new-object Uri("https://outlook.office365.com/EWS/Exchange.asmx") 

# Read the data
Import-Csv $FoldersCSV -Encoding UTF8 | Foreach-Object { 
    $FolderName = $_.FolderName.ToString() 

    Import-Csv $UsersCSV -Encoding UTF8 | Foreach-Object { 
        $EmailAddress = $_.EmailAddress.ToString() 

        # Catch the errors
        trap [System.Exception] { 
            Write-Host ("Error: " + $_.Exception.Message) -foregroundcolor $error
            Add-Content $LogFile ("Error: " + $_.Exception.Message) 
            continue
        } 
        DeleteFolder($EmailAddress) 
    } 
}

The next step is to edit the script if needed.

Edit the Delete Folders Exchange Online PowerShell script

The script will delete the folders completely, and you can’t recover them from deleted items. Do you want to delete the folders to the mailbox Deleted Items folder?

Check lines 82, 83, and 84 for the available options. Change it to your needs.

$oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
#$oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
#$oFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems)

The script will target the mailboxes specified in the Users.txt file. Do you want to target all the mailboxes?

Change line 106 from:

Import-Csv $FoldersCSV -Encoding UTF8 | Foreach-Object { 

to:

Get-Mailbox -ResultSize Unlimited | Foreach-Object {

The next step is to install and connect to Exchange Online.

Connect to Exchange Online PowerShell v2

Start Windows PowerShell or Windows PowerShell ISE as administrator. Install Exchange Online PowerShell v2 and connect to Exchange Online.

Important: If you have MFA enabled on that account, disable it.

PS C:\> Connect-ExchangeOnline -UserPrincipalName admin@exoip.com

The next and last step is to run the script.

Run the Delete Folders Exchange Online PowerShell script

In our example, we do know that user James got all the folders in his mailbox.

Before running the script

  • Subfolder Folder Audio
  • Subfolder Folder Pictures
  • Folder Folder Music
  • Folder Folder Videos
Delete folder in Exchange Online from all mailboxes before

Change the directory to the scripts folder and run the script. A credential prompt will show up. Enter your global admin account or service account that is a member of the application impersonation role.

Delete folder in Exchange Online from all mailboxes credential

It starts searching for the folders in the mailboxes. The output will write to the Log.txt file.

PS C:\> cd \scripts
PS C:\scripts> .\Delete-Folders-EXO.ps1
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder EXISTS in Mailbox: James.Paterson@exoip.com
Deleting Folder: Folder Audio
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder EXISTS in Mailbox: James.Paterson@exoip.com
Deleting Folder: Folder Pictures
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder EXISTS in Mailbox: James.Paterson@exoip.com
Deleting Folder: Folder Music
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder EXISTS in Mailbox: James.Paterson@exoip.com
Deleting Folder: Folder Videos
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com

Rerun the script. It will show that there is nothing to delete.

PS C:\scripts> .\Delete-Folders-EXO.ps1
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com
Searching for folder in Mailbox Name: James.Paterson@exoip.com
Folder does not exist in Mailbox: James.Paterson@exoip.com
Searching for folder in Mailbox Name: Dylan.Piper@exoip.com
Folder does not exist in Mailbox: Dylan.Piper@exoip.com

After running the script

The folders are deleted from the Office 365 mailbox.

Delete folder in Exchange Online from all mailboxes after

Check the Log.txt file if you want to know which folders are deleted from which mailboxes.

Did this article help you to delete a folder in Exchange Online with PowerShell?

Keep reading: Move mailbox to Exchange Online with PowerShell »

Conclusion

In this article, you learned how to delete a folder from all mailboxes in Exchange Online. Not only one folder that you can delete but specific folders that you can give up in a text file. Follow the steps, as shown in the article, before you immediately run the script. The Delete-Folders-EXO.ps1 PowerShell script is excellent for achieving the results.

Did you enjoy this article? You may also like Get shared mailbox size in Office 365 with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 2 Comments

  1. Hi Ali,

    thanks for this nice script, works very well with the regular outlook folders, however I cannot delete a contacts folder, I get an Error: Object cannot be deleted.

    I have an old contact list which is shared with almost 1200 users and I want to have this removed by your script, do you have a suggestion or solution?

    Thanks alot

    Arash Pourwafa

  2. Great post. Really helped me out.

    Can this be modified to also target subfolders as well? In our environment, users may have subfolders named the same for multiple folders. E.g. Inbox/Job1/Phase1 and Inbox/Job2/Phase1. If I wanted to remove Phase1 from ONLY the Job1 folder, could this be done using this script?

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top