Delete Outlook Contact Folder Using Exchange Online - Bypass MFA

Overview

Do you want to delete a folder from all users' Contacts Folders in Exchange Online with PowerShell? And what happens if you have MFA enabled? What if you want to delete specific folders and target specific users? This article will teach you how to delete folders in Exchange Online from users’ Contacts Folders. 

1. Before you start to delete folders in Exchange Online:

1.1 Add impersonation rights in Exchange Online: 

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

Sign 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. 

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

The role group Application-Impersonation has been created successfully. Keep in mind that it may take up to an hour before changes are applied. 

1.2 Install Microsoft Exchange Web Services Managed API 2.2 

Download and install Microsoft Exchange Web Services Managed API 2.2. Save the file to the system. 

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

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

1.3 Create text files for the script 

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

  1. Folders.csv 
  2. Log.txt 
  3. Users.csv 

Open Folders.csv and add Folder Name at the top. Add the folder names on each line. 

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

Open Users.csv and add UserPrincipalName at the top. Add the email addresses to each line. The script will delete the folders from these mailboxes. 

2. Prepare the Delete Folders Exchange Online PowerShell script 

Save the following PowerShell script into the C:\DeleteFolderEXO folder. 

For Example – DeleteFolderEXO.ps1 

[string] $info = "White"
# Color
for informational messages[string] $warning = "Yellow"
# Color
for warning messages[string] $error = "Red"
# Color
for error messages[string] $LogFile = "C:\DeleteFoldersEXO\Log.txt"
# Path of the Log File[string] $FoldersCSV = "C:\DeleteFoldersEXO\Folders.csv"
# Path of the Folders File[string] $UsersCSV = "C:\DeleteFoldersEXO\Users.csv"
# 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 = $_.UserPrincipalName.ToString()
        # Catch the errors
        trap[System.Exception] {
            Write - Host("Error: " + $_.Exception.Message) - foregroundcolor $error
            Add - Content $LogFile("Error: " + $_.Exception.Message)
            continue
        }
        DeleteFolder($EmailAddress)
    }
}

3. Before running the script 

Important: If you have MFA enabled on an account, you will have to create an App Password to bypass the MFA and Login using Created App Password. 

3.1 Let's start with how to create an app password. 

Sign in to the Additional security verification page, and select App passwords. 

Select Create. Type the name of the app that requires the app password – For example Outlook, Exchange Script, etc -- and then select Next

Copy the password from the Your app password page, and then select Close

On the App passwords page, make sure your app is listed. 

Save the App password somewhere safe. We will use it to connect to Exchange Online. You should only have to do this once per app. 

4 Run the Delete Folders Exchange Online PowerShell script 

Now Open PowerShell as Administrator.

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

cd C:\DeleteFoldersEXO
.\DeleteFoldersEXO.ps1 

Important

If you have MFA enabled, in the password field enter the App Password we created before.

It starts searching for the folders in the mailboxes. The output will be written in the Log.txt file. 

After running the script:

The folders will be deleted from Contact Folders. 

Important note:

If the Contact folder contains a huge amount of contacts, then the script will show a time-out error. However, the contact folders will be deleted in a few minutes. Depending on the number of contacts in the folder, this may take up to 10 or 20 minutes. 


Similar Articles