Skip to content

Instantly share code, notes, and snippets.

@dotps1
Last active January 5, 2024 08:07
Show Gist options
  • Save dotps1/d275d79d745170fc57174408e84b2692 to your computer and use it in GitHub Desktop.
Save dotps1/d275d79d745170fc57174408e84b2692 to your computer and use it in GitHub Desktop.
Sync Active Sync Users to group, and remove inactive devices.
$members = Get-ADGroupMember -Identity "ActiveSyncUsers"
foreach ($mailbox in (Get-CASMailbox -Filter { HasActiveSyncDevicePartnership -eq $true } -ResultSize Unlimited)) {
# If the user is disabled, remove all paired devices and ensure the user is removed from the group.
if ((Get-ADUser -Identity $mailbox.DistinguishedName).Enabled -eq $false) {
foreach ($device in (Get-MobileDevice -Mailbox $mailbox.DistinguishedName)) {
Remove-MobileDevice -Identity $device.Identity -Confirm:$false
}
if ($mailbox.DistinguishedName -in $members.DistinguishedName) {
Remove-ADGroupMember -Identity "ActiveSyncUsers" -Members $mailbox.DistinguishedName -Confirm:$false
}
continue
}
# Assume the user has no active devcies, update hasActiveDevice to true if a device has synced in the last 30 days.
$hasActiveDevice = $false
foreach ($device in (Get-MobileDevice -Mailbox $mailbox.DistinguishedName)) {
if ((Get-MobileDeviceStatistics -Identity $device.Identity -ErrorAction SilentlyContinue).LastSuccessSync -lt (Get-Date).AddDays(-30)) {
Remove-MobileDevice -Identity $device.Identity -Confirm:$false
} else {
$hasActiveDevice = $true
}
}
# If the user has an active device, ensure they are in the group.
if ($hasActiveDevice -and $mailbox.DistinguishedName -notin $members.DistinguishedName) {
Add-ADGroupMember -Identity "ActiveSyncUsers" -Members $mailbox.DistinguishedName
} elseif (-not $hasActiveDevice -and $mailbox.DistinguishedName -in $members.DistinguishedName) {
Remove-ADGroupMember -Identity "ActiveSyncusers" -Members $mailbox.DistinguishedName -Confirm:$false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment