Remove user from Office 365 Groups

Ackles
Ackles used Ask the Experts™
on
Hi,
I need a powershell script to remove user from all groups, Distribution & Office 365.
I have the following code, works fine for Distribution, but not for Office 365 groups...
Can someone Please Help?

$name = Read-Host -Prompt "FirstName.LastName"
$email = "@abc.com"
$user = $name + $email

$mailbox=get-mailbox $user

					$dgs= Get-DistributionGroup
                    $ugs= Get-UnifiedGroup
					foreach($dg in $dgs){
					    $DGMs = Get-DistributionGroupMember -identity $dg.Identity
					    foreach ($dgm in $DGMs){
					        if ($dgm.name -eq $mailbox.name){
					       
					            write-host 'User Found In Group' $dg.identity
					              Remove-DistributionGroupMember $dg.Name -Member $user -Confirm:$False 
					        }
					    }
					}

					foreach($ug in $ugs){
					    $UGMs = Get-UnifiedGroup | where { (Get-UnifiedGroupLinks $_.Alias -LinkType Members | foreach {$_.name}) -contains $mailbox.Alias}
					    foreach ($ugm in $UGMs){
					        if ($ugm.name -eq $mailbox.name){
					       
					            write-host 'User Found In Group' $ug.identity
					              Remove-UnifiedGroupLinks -identity $UGMs.alias -LinkType Member -Links $mailbox -Confirm:$False 
					        }
					    }
					}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
You are using an incorrect syntax to build the $UGMs variable, $_.Alias will not resolve within the pipeline unless you put a foreach statement first. Anyway, there's a much easier/faster method to get the groups of which particular user is a member:

Get-Recipient -Filter "Members -eq 'CN=user,OU=tenant.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR03A001,DC=prod,DC=outlook,DC=com'" 

Open in new window


Simply get the user's DN and replace it in the above. You can use the -RecipientTypeDetails parameter to filter out just DGs or just Office 365 Groups and then use the corresponding cmdlet to remove the user accordingly.

Author

Commented:
Sorry, but can you please modify my script?

Author

Commented:
Any Help?
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Most Valuable Expert 2015
Distinguished Expert 2018
Commented:

Author

Commented:
Thanks Vasil,
I tried the script, it does job for DG, but for O365 groups it says, No matching security Groups found for user.... Skipping?

Author

Commented:
My bad. Works perfectly!!!
Thanks a lot

Author

Commented:
Awesome

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial