This seems pretty optimal to me given how simple it is, only a question, why the Foreach foreach
? Do you expect Get-MailContactGet-MailContact
to return multiple contacts ?
I don't have an AD I can test it against, but I'd be curious to know if "reversing" the operation by removing the member from the groups instead of removing the membership from the user could make it faster:
$ADContact = Get-MailContact <name> | Get-ADObject -Properties memberof
# Loop through all the groups and remove the user from them.
foreach ($group in $ADContact.MemberOf) {Remove-ADGroupMember -Identity $group -Member $ADContact}