Remove a user's oldest ActiveSync device

A few weeks ago, I saw something come up for a peer that needed a way to manage the maximum number of ActiveSync devices that a user had connected in Office 365.  Using only native Exchange policies, we can't do that (MDM solutions solve this problem by manning the Exchange ActiveSync quarantine).  If it was an Exchange on-premises deployment, we could manage it via throttling policies.

I thought it was an interesting problem and came up with a solution (though not terribly elegant) based on these constraints:

  • Specify maximum number of devices for a user
  • Remove all devices over specified number, sorted by last successful sync

Here's what I came up with--anyone have better solutions?

 [int]$MaxDevices = "5"
# Test on a single user
[array]$Devices = Get-MobileDevice -Mailbox aguilmette@tenant.onmicrosoft.com
# Find All Devices
# [array]$Devices = Get-MobileDevice -Mailbox -ResultSize Unlimited
# Find unique users
$Users = $Devices.UserDisplayName | Sort -Unique
Foreach ($User in $Users)
     {
     # Find all devices associated with a user
     $UserDevices = @()
     $UserDevices += Get-MobileDevice -Mailbox $User
     While ($UserDevices.Count -gt $MaxDevices)
          {
          $UserArrayOfDevices = @()
          Foreach ($Device in $UserDevices)
              {
              Write-Host $User has $UserDevices.Count ActiveSync devices
              $UserArrayOfDevices += Get-MobileDeviceStatistics $Device.Identity
              $UserArrayOfDevices = $UserArrayOfDevices | Sort -Property LastSuccessSync
              }
          Remove-MobileDevice -Identity $UserArrayOfDevices[0].Identity #-Confirm:$False
          $UserDevices = @()
          $UserDevices += Get-MobileDevice -Mailbox $User
          }
     }