PowerShell: Remove outdated ActiveSync Devices

Howdy Exchange Administrators!

How often have you had to undertake the task of cleaning stale device from user mailboxes and how often did you need to go and manually delete the AirSync-* folders via either MFCMAPI or EWSEditor? Probably many.

As some administrators (legitimately) like to keep the mailboxes tidy or they might have a business/process requirement for such a task to be done, it was about time to make some automation.

This should also help in these scnearios where the Remove-MobileDevice fails due to some missing dependancies (such as a missing container in AD, within the user object).

It can also be used to just remove any partnership the mailbox has got (i.e. for troubleshooting purposes) should you wish the target user to re-provision all his devices.


Now, let's get to the sample script.


What does it need?

  1. The target mailbox PrimarySmtpAddress and the number of days before considering a device "outdated";
  2. The PowerShell URL as well as the EWS URL (the latter can be auto-discovered if missing);
  3. The credentials of an Administrator who has got access to PowerShell as well as has been granted Full Access or Impersonation right on the target mailbox or the credential of the end user (all the Cmdlet and the EWS methods can run as "self");
  4. Your kind confirmation that the outdated devices can be removed; if the ConfirmDeletion switch is not used, all the operations but the actual deletions/removals would be performed.


How does it do that?

  1. It checks first what devices the end-user has got associated to his mailbox (Get-MobileDevice -Mailbox <PrimarySmtpAddress>);
  2. For each device it checks the LastSuccessSync attribute (Get-MobileDeviceStatistics -Identity <id>). If that is set to a date more than the desired threshold (i.e. 7 days) it proceeds with the removal;
  3. The removal is done in 2 parts, firstly it runs a Remove-MobileDevice <DeviceId>, then it locate the AirSync folder associated and, if present it removes the same via EWS;
  4. Lastly, it scans the target mailbox looking for other devices (perhaps not listed in the Get-MobileDeviceStatistics output) and if necessary proceeds with the deletion.


The last step is actually quite useful since, with Exchange 2010 the partnership was stored in a AirSync folder right underneath the mailbox root. With Exchange 2013 and later versions such a folder has been moved under the folder ExchangeSyncData. This implies that if a mailbox is migrated from Exchange 2010 to Exchange 2013, there would be a folder with the up-to-date partnership within the ExchangeSyncData and another, just left over, under the mailbox root. While this is harmless and can be safely left at its place, there is no actual need for it.


Let's run it.


There are different ways to run it, most of which are available in the script's help.


Here a regular user (Test@Contoso.com) runs it against his own mailbox.

The user does not need any special permission as by default he should be able to run PowerShell cmdlet whose scope is the user's mailbox itself; same applies to EWS. This would be a trial run (report only) as the parameter -ConfirmDeletion is not specified.


$UserCred  = Get-Credential
.\Remove-StaleMobileDevices.ps1 -Mailbox "Test@Contoso.com" -Credentials $UserCred -PsUrl "https://outlook.office365.com/PowerShell/" -PSAuth Basic -EwsUrl "https://outlook.office365.com/EWS/Exchange.asmx" -LastSyncedMoreThanDay 7 -LogFile .\LogFile.txt


In the following scenario the Administrator will be looking to clear out stale devices from "Test@Contoso.com". The Administrator is leveraging Delegate Access (a.k.a. FullAcceess) to act on the end-user's mailbox. This implies the permission must be explicitly granted prior to run this script. This would be a trial run (report only) as the parameter -ConfirmDeletion is not specified.

$AdminCred  = Get-Credential
.\Remove-StaleMobileDevices.ps1 -Mailbox "Test@Contoso.com" -Credentials $AdminCred -PsUrl "https://outlook.office365.com/PowerShell/" -PSAuth Basic -EwsUrl "https://outlook.office365.com/EWS/Exchange.asmx" -LastSyncedMoreThanDay 7 -LogFile .\LogFile.txt


The following sample demonstrates how the Administrator perform the same action by using Impersonation as opposed to Delegate Access. Again, this would be a trial since the parameter -ConfirmDeletion is not specified.

$AdminCred  = Get-Credential
.\Remove-StaleMobileDevices.ps1 -Mailbox "Test@Contoso.com" -Credentials $AdminCred -PsUrl "https://outlook.office365.com/PowerShell/" -PSAuth Basic -EwsUrl "https://outlook.office365.com/EWS/Exchange.asmx" -LastSyncedMoreThanDay 7 -Impersonate -LogFile .\LogFile.txt


The following is probably the scenario where this automation helps the most.

The Administrator is clearing out the stale devices from all the mailboxes in the organization. At this time Impersonation is leveraged as it's more straight forward to implement and better fits with large workloads (as adding and removing thereafter FullAccess permission requires more steps and is more prone to human errors).

 $AdminCred  = Get-Credential
 Get-Mailbox | Select-Object PrimarySmtpAddress | %{.\Remove-StaleMobileDevices.ps1 -Mailbox $_.PrimarySmtpAddress -Credentials $AdminCred -PsUrl "https://mail.contoso.com/PowerShell/" -PSAuth Basic -EwsUrl "https://mail.contoso.com/EWS/Exchange.asmx" -LastSyncedMoreThanDay 7 -Impersonate -LogFile .\LogFile.txt}


The above should cover most of the scenarios, anyway more example are available in the Script help file. Don't hesitate to run the following to know more about how you can use this.

Get-Help .\Remove-StaleMobileDevices.ps1 -Detailed




Please download the file here: Remove-StaleMobileDevices.




The script has been developed (and validated) against Exchange 2013, Exchange 2016 and Exchange Online. As such the decision to use the -MobileDevice* cmdlet has been made since this is the set of commands supported by the currently supported Exchange releases. If you wish to run the script against Exchange 2010 you need to make a quick change and change the cmdlets to -ActiceSync*.

These commands have been deprecated and therefore there was no point in making the script retro-compatible, however, should you wish to use it against Exchange 2010 you can do a quick "Replace All" and convert the "-MobileDevice" to "-ActiceSync"; don't forget to test it please.


Comments (6)

  1. Cristian says:

    good job

  2. Peter Dong says:

    Is there any suggestion for below issue error message ? thank you~

    ERROR: Unable to establish EWS session

    1. Hi Peter,

      That is probably due to connectivity issues.

      1. Matthew Draycott says:

        I get the same error when running the script but I can connect to the ewsurl from a browser so I don’t think it’s connectivity.

        .\Remove-StaleMobileDevices.ps1 -Mailbox “user@domain.com” -Credentials $AdminCred -PsUrl “https://outlook.office365.com/powershell-liveid/” -PSAuth Basic -EwsUrl “https://outlook.office365.com/EWS/Exchange.asmx” -LastSyncedMoreThanDay 7 -LogFile .\LogFile.txt

        1. Matthew Draycott says:

          We’ve fix it, you just need to install EWS Managed API (https://www.microsoft.com/en-us/download/details.aspx?id=42951).

  3. Hi mates,

    I´ve tried to adapt it to Ex2010 SP3, but although I´ve done the suggested modification, I still have this error:

    INFO: Mailbox has got devices
    ERROR: Unable to fetch Device Statistics for /
    ERROR: Exception: Cannot bind argument to parameter ‘Identity’ because it is null.
    INFO: Need to remove / as it last synced on
    INFO: RemoveDeviceviaPS
    INFO: Trial run; would have been removed from
    INFO: RemoveDeviceviaEWS
    ERROR: Unable to perform deletion for /
    ERROR: Exception: Exception calling “Bind” with “2” argument(s): “Exchange Server doesn’t support the requested version.”
    INFO: LookForHiddenDevicesViaEWS
    ERROR: Unable to lcoate if there are stale devices left over in
    ERROR: Exception: Exception calling “Bind” with “2” argument(s): “Exchange Server doesn’t support the requested version.”
    INFO: Disconnecting from PowerShell
    INFO: Execution completed

    Could somebody help me?
    I´m in a hurry
    Thanks in advance

Skip to main content