This will be a quick how-to guide on removing old/stale ActiveSync devices from Microsoft Exchange.
Note 1: I have only run this on an on-premises Exchange 2007 server so I am not sure if it will work in 2010, 2013 or Office 365 but hopefully the script will come in handy anyway
Note 2: This is my first ever PowerShell script so I am sure there are better ways of doing this but it does the job!
Okay so if you want to run a report on old devices (I have defined old as no successful sync in the past 30 days but you can change this to whatever you want) before you go ahead and remove them, run the following command:
Get-Mailbox | ForEach {Get-ActiveSyncDeviceStatistics -Mailbox:$_.Identity} | where {$_.LastSuccessSync -lt ((Get-Date).AddDays(-30))}
To actually remove these devices (this command removes the relationship between the device and Exchange – it will NOT wipe the device) run this command:
# Assign the full identity string for each of the old devices to the $staleDevices variable - this identity string is required for the Remove-ActiveSyncDevice cmdlet
$staleDevices = Get-Mailbox | ForEach {Get-ActiveSyncDeviceStatistics -Mailbox:$_.Identity} | where {$_.LastSuccessSync -lt ((Get-Date).AddDays(-30))} | select -expand Identity
# Loop through the identities and pass them in to Remove-ActiveSyncDevice. The -confirm at the end forces the command to go through. Remove it if you want to manually confirm each removal
foreach ($device in $staleDevices) {Remove-ActiveSyncDevice -Identity $device -confirm:$false}