Need to create a script to get all O365 groups a user is a member of, using user’s samaccountname. And then remove the user’s membership from all those O365 groups.

Any suggestions?

@garygreenberg @jitensh

5 Spice ups

I am following because this would be amazing!

Post what you have & we can help get you going in the right direction.

1 Spice up

Did you try anything? something like that?

cannot test it but try

$useremailaddress='user@domain.com'
foreach ($Group in (Get-MsolGroup -all)){
Get-MsolGroupMember -all -GroupObjectId $Group.ObjectId | where {$_.Emailaddress -eq "user@domain.com"}|select @{n='Group';e={$Group.Displayname}}
}

$Group = Get-MsolGroup -SearchString "MyGroup","Group2" ,"Group3" # paste all group names
$User = Get-MsolUser -UserPrincipalName "$useremailaddress"
foreach($grp in $Group){
Remove-MsoLGroupMember -GroupObjectId $Grp.ObjectId -GroupMemberType User -Groupmemberobjectid $user.ObjectId
}

Just wanted to mentiond to add some checks and balances before you actually execute the “Remove-MsolGroupMember” Cmdlet. Unfortunately, there’s no -WhatIf parameter so I would do a simple echo “removing user abc from group xyz” and then once you’re ok with the results uncomment the Cmdlet to actually execute it.

Otherwise a simple typo can really ruin your day.

I have this script :


Param(
[Parameter(Mandatory=$True)]
[string]$SamAccount,
[string]$RequestedItem
)

#Variables
$userDetails = “”
$userDetails = Get-ADUser $SamAccount -Properties * | select-object userprincipalname

$UserUPN = “testuser1234@contoso.com

#Connect to AzureAD
Connect-AzureAD -Credential (Get-Credential) | Out-Null

#Get all Azure AD Unified Groups
$AADGroups = Get-AzureADMSGroup -Filter “groupTypes/any(c:c eq ‘Unified’)” -All:$true

#Get the Azure AD User
$AADUser = Get-AzureADUser -Filter “UserPrincipalName eq ‘$UserUPN’”

#Check each group for the user
ForEach ($Group in $AADGroups)
{
$GroupMembers = (Get-AzureADGroupMember -ObjectId $Group.id).UserPrincipalName
If ($GroupMembers -contains $UserUPN)
{
#Remove user from Group
Remove-AzureADGroupMember -ObjectId $Group.Id -MemberId $AADUser.ObjectId
Write-Output “$UserUPN was removed from $($Group.DisplayName)”
}
}


I need to use it with another script… where another script would be calling in this script and pass on the user’s SAMACCOUNT name value to this script, and this script would have to check what all O365 groups that Samaccount is a member of, and then remove the membership from those groups. Any suggestions?

@jitensh @tb33t