How to cleanup stale Active Sync Devices in Exchange 2010

# Powershell script to clear stale ActiveSync partnerships

# Are Romøren, 07042011

# Get all CAS-enabled mailboxes in Exchange organization and filter on LastSuccessSync

# Must be run from an Exchange server with Mailbox Role installed, account needs Exchange administrative privileges

# (Get-Date).AddDays("-7") - specify "older than"-parameter (current example will remove all partnerships older than 1 week)

Get-CASMailbox -ResultSize unlimited -Filter{(HasActiveSyncDevicePartnership -eq $true) -AND (name -notlike "cas_*") -AND (name -notlike "DiscoverysearchMailbox*")} | ForEach {Get-ActiveSyncDeviceStatistics -Mailbox:$_.Identity | Where-Object {$_.LastSuccessSync -le (Get-Date).AddDays("-7")}} | Remove-ActiveSyncDevice